本文介绍了"using"指令应该在名称空间之内还是之外?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在某些C#代码上运行 StyleCop ,并且它一直在报告我的指令应位于名称空间内.

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

using指令放在名称空间而不是名称空间之外是不是出于技术原因?

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

推荐答案

两者之间实际上存在(细微)差异.假设您在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
    {
    }
}

编译器在查看命名空间之外的那些using指令之前先搜索Outer,因此它将找到Outer.Math而不是System.Math.不幸的是(或幸运的是?),Outer.Math没有PI成员,因此File1现在已损坏.

The compiler searches Outer before looking at those using directives 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.

如果将using放在名称空间声明中,则情况会发生变化,如下所示:

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,然后再搜索Outer,找到System.Math,一切都很好.

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

有些人认为Math对于用户定义的类来说可能是个坏名字,因为System中已经存在一个了.这里的重点只是 有所不同,并且会影响代码的可维护性.

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.

有趣的是,如果Foo在命名空间Outer中而不是在Outer.Inner中,会发生什么.在这种情况下,无论using到哪里,在File2中添加Outer.Math都会破坏File1.这意味着编译器在查看任何using指令之前先搜索最内层的命名空间.

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 directive.

这篇关于"using"指令应该在名称空间之内还是之外?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-12 05:31