简体   繁体   English

c#中命名空间的幕后花絮?

[英]behind the scenes of namespace in c#?

using System;

namespace HelloWorld
{
    partial class Program
    {
          static void Main(string[] args)
        {
            Console.WriteLine();
        }
    }
} 


my question is when we use using System at the top,are all the codes in that namespace loaded behind the scene in this namespace(HelloWorld)???我的问题是,当我们在顶部使用 using System 时,该命名空间中的所有代码是否都加载到此命名空间(HelloWorld)中的场景后面???

using does not change how code is loaded. using不会改变代码的加载方式。 It only changes which namespaces are allowed to be implicitly assumed when the compiler parses and compiles the code.它只更改在编译器解析和编译代码时允许隐式假定的命名空间。 I think the generated output from the compiler is the same as if you don't use using , but instead explicitly write it the full name of every reference.我认为编译器生成的输出与您不使用using ,而是明确地将每个引用的全名写入它。

But to answer your other question, yes, every object in the namespace is affected, so you should be able to refer to Console without explicitly including System.但是,为了回答您的其他问题,是的,命名空间中的每个对象都受到影响,所以你应该能够引用Console没有明确包括System. before it.在它之前。 Keep in mind that using is different than adding a reference.请记住, using与添加引用不同。 If you don't have a reference to System.dll, you'll still get an error.如果您没有对 System.dll 的引用,您仍然会收到错误消息。

Namespaces does nothing to the compiled program, it is just a way for you to organize your code.命名空间对编译后的程序没有任何作用,它只是您组织代码的一种方式。 Nothing is loaded behind the scene.在幕后没有加载任何东西。 When two classes are in the same namespace, you dont need to add a using to be able to reference that class.当两个类在同一个命名空间中时,您不需要添加 using 来引用该类。

Ofcourse, if the namespace you are using is located in an assembly that isn't automatially referenced you will have to add a reference also.当然,如果您使用的命名空间位于未自动引用的程序集中,则还必须添加引用。 'using' does not do that for you. “使用”不会为您做到这一点。

Here's a good reference for namespaces:这是命名空间的一个很好的参考:

https://www.programiz.com/csharp-programming/namespaces https://www.programiz.com/csharp-programming/namespaces

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM