There is actually a (subtle) difference between the two.
(两者之间实际上存在(细微)差异。)
Imagine you have the following code in File1.cs: (假设您在File1.cs中具有以下代码:)
// File1.cs
using System;
namespace Outer.Inner
{
class Foo
{
static void Bar()
{
double d = Math.PI;
}
}
}
Now imagine that someone adds another file (File2.cs) to the project that looks like this:
(现在,假设有人将另一个文件(File2.cs)添加到项目中,如下所示:)
// File2.cs
namespace Outer
{
class Math
{
}
}
The compiler searches Outer
before looking at those using
directives outside the namespace, so it finds Outer.Math
instead of System.Math
.
(编译器先搜索Outer
然后再using
命名空间之外的指令查看它们,因此它将找到Outer.Math
而不是System.Math
。)
Unfortunately (or perhaps fortunately?), Outer.Math
has no PI
member, so File1 is now broken. (不幸的是(或者幸运的是?), Outer.Math
没有PI
成员,因此Outer.Math
现在已损坏。)
This changes if you put the using
inside your namespace declaration, as follows:
(如果将using
放在名称空间声明中,则情况会发生变化,如下所示:)
// File1b.cs
namespace Outer.Inner
{
using System;
class Foo
{
static void Bar()
{
double d = Math.PI;
}
}
}
Now the compiler searches System
before searching Outer
, finds System.Math
, and all is well.
(现在,编译器在搜索Outer
之前先搜索System
然后找到System.Math
,一切都很好。)
Some would argue that Math
might be a bad name for a user-defined class, since there's already one in System
;
(有人会认为Math
对于用户定义的类来说可能是个坏名字,因为System
已经有一个了。)
the point here is just that there is a difference, and it affects the maintainability of your code. (这里要说的就是这样是有区别的,它会影响你的代码的可维护性。)
It's also interesting to note what happens if Foo
is in namespace Outer
, rather than Outer.Inner
.
(有趣的是,如果Foo
在命名空间Outer
而不是Outer.Inner
,会发生什么。)
In that case, adding Outer.Math
in File2 breaks File1 regardless of where the using
goes. (在这种情况下,无论using
在何处,在Outer.Math
中添加Outer.Math
破坏Outer.Math
。)
This implies that the compiler searches the innermost enclosing namespace before it looks at any using
directive. (这意味着编译器在查看任何using
指令之前先搜索最里面的命名空间。)