命名空间和使用指令
如果我有一个像这样的命名空间:
namespace MyApp.Providers
{
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Globalization;
}
这是否意味着如果我创建具有相同命名空间的其他文件和类,则 using 语句将被共享,并且我不需要再次包含它们?
如果是的话,这不是让管理有点头疼吗?
If I have a namespace like:
namespace MyApp.Providers
{
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Globalization;
}
Does this mean that if I create other files and classes with the same namespace, the using statements are shared, and I don't need to include them again?
If yes, isn't this a bit of a management headache?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
不,它只适用于文件内的命名空间部分。 不适用于命名空间内的所有文件。
如果将 using 语句放在命名空间之外,则无论命名空间如何,它都适用于整个文件。
它还将首先搜索命名空间内的Usings,然后再转到外部作用域。
No, it's only good for the namespace section inside the file. Not for all files inside the namespace.
If you put the using statement outside the namespace, then it applies to the entire file regardless of namespace.
It will also search the Usings inside the namespace first, before going to the outer scope.
您需要在要使用它们的每个文件中为要引用的任何类指定 using 指令,而无需限定。
参考:
You need to specify the using directive for any classes that you want to reference without qualification in each file where you want to use them.
Reference:
不,它没有,所以不,它不是。
考虑一下这样一个事实:在
namespace
声明之外,您位于全局命名空间中。 源文件该区域中的using
语句是否会影响其他源文件中的全局命名空间?No, it doesn't, and so no, it isn't.
Consider the fact that outside the
namespace
declaration, you are in the global namespace. Dousing
statements in that region of the source file affect the global namespace in other source files?不可以。您需要在每个类中包含命名空间(部分类除外)。
旁注:您正在将 using 语句放入命名空间中,这是一种非常好的做法。 这是非常好的语法。
保持良好的工作。
No. You'll need to include the namespaces in every class except on partial classes.
One side note: you're doing a very good practice of putting the using statements inside the Namespace. That's very good syntax.
Keep up the good work.
using 语句对于它们出现的代码文件是有效的,但有一点小小的改变; 如果将 using 语句放在命名空间内,它们将被限制在该命名空间的范围内,但仍然只能在同一代码文件内。
The using statements are valid for the code file in which they appear, with a minor twist; if you put the using statements inside the namespace, they are limited to the scope of that namespace, but still only within the same code file.
使用仅适用于当前文件。 无论它们是在命名空间声明内部还是外部,差别很小:
类型的查找顺序如下:
结果,该程序将正常编译:
但如果将
using System;
移至顶部,则编译将失败(MyProject.Console.WriteLine 不存在) )。Usings only apply to the current file. Whether they're inside or outside the namespace declaration makes only a small difference:
The lookup order for types is as follows:
As a result, this program will compile fine:
But if you move the
using System;
to the top, then the compilation will fail (MyProject.Console.WriteLine doesn't exist).