如果“使用”的语句是内部或外部的命名空间?语句、空间

2023-09-02 01:16:24 作者:将往事与酒吞

我已经运行了StyleCop 了一些C#code,它不断地汇报我的使用语句应该是命名空间中。

I have been running StyleCop over some C# code, and it keeps reporting that my using statements should be inside the namespace.

有没有技术理由把使用语句中,而不是命名空间?

Is there a technical reason for putting the using statements inside instead of outside the namespace?

推荐答案

其实是有两个之间的(细微)的区别。试想一下,你有以下code在File1.cs:

There is actually a (subtle) difference between the two. Imagine you have the following code in File1.cs:

// File1.cs
using System;
namespace Outer.Inner
{
    class Foo
    {
        static void Bar()
        {
            double d = Math.PI;
        }
    }
}

现在想象一下某人增加了另一个文件(File2.cs),以看起来像这样的项目:

Now imagine that someone adds another file (File2.cs) to the project that looks like this:

// File2.cs
namespace Outer
{
    class Math
    {
    }
}

编译器的搜索看着那些以前使用命名空间之外语句,所以它找到 Outer.Math 而不是 System.Math 。不幸的是(或者幸运?), Outer.Math 没有 PI 成员,所以文件1,现在坏了。

The compiler searches Outer before looking at those using statements outside the namespace, so it finds Outer.Math instead of System.Math. Unfortunately (or perhaps fortunately?), Outer.Math has no PI member, so File1 is now broken.

这改变了,如果你把使用命名空间声明中,如下所示:

This changes if you put the using inside your namespace declaration, as follows:

// File1b.cs
namespace Outer.Inner
{
    using System;
    class Foo
    {
        static void Bar()
        {
            double d = Math.PI;
        }
    }
}

现在的编译器的搜索系统前搜索,找到 System.Math ,一切都很好。

Now the compiler searches System before searching Outer, finds System.Math, and all is well.

有人会说,数学可能是一个坏的名称为用户定义的类,因为有已经之一系统;这里的要点就是,有的是的差异,它会影响你的code中的可维护性。

Some would argue that Math might be a bad name for a user-defined class, since there's already one in System; the point here is just that there is a difference, and it affects the maintainability of your code.

这也是值得注意的会发生什么,如果在命名空间,而不是 Outer.Inner 。在这种情况下,加入 Outer.Math file2中打破文件1,无论其中使用去。这意味着,编译器搜索最内层空间,它看起来在任何使用语句之前。

It's also interesting to note what happens if Foo is in namespace Outer, rather than Outer.Inner. In that case, adding Outer.Math in File2 breaks File1 regardless of where the using goes. This implies that the compiler searches the innermost enclosing namespace before it looks at any using statements.