Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
581 views
in Technique[技术] by (71.8m points)

c# - “ using”指令应该在名称空间之内还是之外?(Should 'using' directives be inside or outside the namespace?)

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

(我一直在通过某些C#代码运行StyleCop ,并且一直在报告我的using指令应该在名称空间内。)

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

(是否有技术上的理由将using指令放在名称空间的内部而不是外部?)

  ask by benPearce translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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指令之前先搜索最里面的命名空间。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...