第一个在命名空间x范围内具有y的作用域,第二个在整个文件中具有y的作用域,因此可能还会涉及其他命名空间。如果您每个文件只保留一个命名空间(我想这是约定),那么通常没有真正的区别[但请参见Marc关于不同名称的不同类型在不同命名空间中发生冲突的评论]。如果使用StyleCop,则应将usings保留在命名空间内。
using
语句放在namespace
块内,可以将其作用域限制在该块中。这会影响许多事情。
using
statement is only valid within the block, so if there were other namespace
blocks, they wouldn't be affected.using
can be shortened based on the outer namespace
block. So using x.y;
outside of the namespace can just be expressed as using y;
inside of the namespace x
block.using
inside of the namespace causes the compiler to guarantee that the specified namespace isn't overwritten. For example:
using Guid = System.Guid;
namespace Sample
{
public class Guid {}
public class Program
{
public static void Main()
{
Console.WriteLine(new Guid());
}
}
}
Guid
is being instantiated. If the using
statement is inside of the namespace
block, however, a compiler error is thrown.请参阅相关的StyleCop文档以获取更完整的讨论。