我一直在一些C#代码上运行StyleCop,它不断报告我的using指令应该在命名空间中。

是否有技术原因将using指令放在命名空间内部而不是外部?


当前回答

我遇到了一条皱纹(其他答案中没有提到):

假设您有以下名称空间:

有些东西。其他父级.某些.其他

当您在命名空间Parent之外使用Something.Other时,它指的是第一个(Something.Other)。

但是,如果在该命名空间声明中使用它,它将引用第二个(Parent.Something.Other)!

有一个简单的解决方案:添加“global::”前缀:docs

namespace Parent
{
   using global::Something.Other;
   // etc
}

其他回答

我遇到了一条皱纹(其他答案中没有提到):

假设您有以下名称空间:

有些东西。其他父级.某些.其他

当您在命名空间Parent之外使用Something.Other时,它指的是第一个(Something.Other)。

但是,如果在该命名空间声明中使用它,它将引用第二个(Parent.Something.Other)!

有一个简单的解决方案:添加“global::”前缀:docs

namespace Parent
{
   using global::Something.Other;
   // etc
}

正如杰佩·斯蒂格·尼尔森(Jeppe Stig Nielsen)所说,这条线索已经有了很好的答案,但我认为这一相当明显的微妙之处也值得一提。

使用在名称空间中指定的指令可以缩短代码,因为它们不需要像在外部指定时那样完全限定。

以下示例之所以有效,是因为类型Foo和Bar都位于同一个全局命名空间Outer中。

假设代码文件Foo.cs:

namespace Outer.Inner
{
    class Foo { }
}

和Bar.cs:

namespace Outer
{
    using Outer.Inner;

    class Bar
    {
        public Foo foo;
    }
}

这可能会省略using指令中的外部命名空间,简称:

namespace Outer
{
    using Inner;

    class Bar
    {
        public Foo foo;
    }
}

根据Hanselman-使用指令和装配加载。。。和其他此类物品在技术上没有区别。

我的偏好是将它们放在名称空间之外。

将其放在名称空间中会使声明成为文件的该名称空间的本地声明(如果文件中有多个名称空间),但如果每个文件只有一个名称空间,那么它们在名称空间外部还是内部都没有太大区别。

using ThisNamespace.IsImported.InAllNamespaces.Here;

namespace Namespace1
{ 
   using ThisNamespace.IsImported.InNamespace1.AndNamespace2;

   namespace Namespace2
   { 
      using ThisNamespace.IsImported.InJustNamespace2;
   }       
}

namespace Namespace3
{ 
   using ThisNamespace.IsImported.InJustNamespace3;
}

另一个我认为没有被其他答案涵盖的微妙之处是,当你有一个同名的类和命名空间时。

当您在名称空间中导入时,它将找到该类。如果导入在命名空间之外,那么将忽略导入,并且类和命名空间必须完全限定。

//file1.cs
namespace Foo
{
    class Foo
    {
    }
}

//file2.cs
namespace ConsoleApp3
{
    using Foo;
    class Program
    {
        static void Main(string[] args)
        {
            //This will allow you to use the class
            Foo test = new Foo();
        }
    }
}

//file3.cs
using Foo; //Unused and redundant    
namespace Bar
{
    class Bar
    {
        Bar()
        {
            Foo.Foo test = new Foo.Foo();
            Foo test = new Foo(); //will give you an error that a namespace is being used like a class.
        }
    }
}