gpt4 book ai didi

c# - 使用语句和添加引用有什么区别?

转载 作者:可可西里 更新时间:2023-11-01 02:58:58 28 4
gpt4 key购买 nike

在 Visual Studio 中,什么时候必须添加对 dll 的引用?我总是尽量在我的项目中使用最少的引用资料,我尽量只包含真正必要的引用资料。

如果我的源代码中有 using 语句,我会认为我只需要一个引用。但这还不够。

例如,我有一个非常简单的程序,它使用 System 和 Microsoft.Practices.EnterpriseLibrary.Data:

using System;
using Microsoft.Practices.EnterpriseLibrary.Data;

public class SimpleConnection {
private static void Main() {
var database = DatabaseFactory.CreateDatabase();
var command =
database.GetSqlStringCommand(
"select table_name from information_schema.tables");
using (var reader = database.ExecuteReader(command)) {
while (reader.Read()) {
Console.WriteLine(reader.GetString(0));
}
}
}
}

我会认为我只需要引用 System 和 Microsoft.Practices.EnterpriseLibrary.Data。但事实并非如此。如果我不引用 System.Data,代码将无法编译。

The type 'System.Data.Common.DbCommand' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.

我如何才能事先知道我必须添加对我未使用的内容的引用?

最佳答案

引用告诉编译器在哪里寻找要导入的类型。使用语句告诉编译器在哪里寻找“全名”

所以你可以输入

 using System.Text

StringBuilder sb;
// ...

 System.Text.StringBuider sb;
// ...

但无论哪种方式,您都必须有对 System.dll 的引用(或者它是 StringBuilder 的 mscorlib 吗?)。没有 ref,编译器不知道可用的类型。

关于c# - 使用语句和添加引用有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6192518/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com