为什么 C# 标准库需要程序集引用和导入?
我必须为标准库执行这两项操作的原因是什么?对于我使用过的每一种其他语言,我只需要执行一种即可访问标准库。
What is the reason that I have to do both of these for the standard libraries? For every other language that I have used, I only have to do one to access standard libraries.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
程序集引用使程序集中的代码可用于另一个程序集。
using
指令使另一个命名空间的类型可用于给定的源文件。这些是完全不同的概念。如果您愿意,您可以不使用usings
指令并使用完全限定的类型名称。同样,可以使用usings
指令来引用同一程序集中的其他命名空间。此外,出于本次讨论的目的,Java 和 C# 之间的程序集/jar 和 usings/import 之间存在完美的类比。所以 C# 在这里并不是独一无二的。
An assembly reference makes the code in the assembly available to another assembly. A
using
directive makes the types of another namespace available to a given source file. These are completely separate concepts. If you were inclined, you could get away with never using theusings
directive and using fully-qualified type names. Similarly, it is possible to use theusings
directive to refer to other namespaces within the same assembly.Also, there is a perfect analog between assemblies/jars and usings/import between Java and C# for the purposes of this discussion. So C# is hardly unique here.
程序集引用是平台的概念,而命名空间导入是语言的概念。
您需要向编译器提供程序集引用,因为它需要知道您正在使用的库代码在哪里。但
using
指令纯粹是可选的。这两个都可以正常编译:示例 1:
示例 2:
using
指令的作用只是为了让您不必到处编写完全限定的名称。Assembly references are a concept of the platform, while a namespace import is a concept of the language.
You need to give an assembly reference to the compiler because it needs to know where the library code you're using is. But the
using
directive is purely optional. Both these will compile fine:Example 1:
Example 2:
The
using
directive serves only to save you from having to write fully qualified names all over the place.Visual Studio 需要引用的某些属性来决定如何在运行时解析它以及如何在构建项目时部署它。这些选项不能通过简单的导入语句来暗示。
Visual studio needs certain attributes of a reference to decide how to resolve it at runtime and how to deploy it when building the project. These options cannot be implied by a simple import statement.
您需要引用程序集,让编译器知道在哪里找到它们导出的类型。您不需要包含命名空间,但它使代码更易于阅读,因为您可以避免使用完全限定的名称。此外,由于每个程序集可能公开多个名称空间,因此这是对相关类型进行分组的便捷方法。
You need to reference the assemblies to let the compiler know where to locate the types they export. You don't need to include namespaces, but it makes code easier to read as you can avoid fully qualified names. Additionally since each assembly may expose several namespaces it is a convenient way to group related types.