.NET 命名空间和 using 语句

14
2个回答

15

第一个在命名空间x范围内具有y的作用域,第二个在整个文件中具有y的作用域,因此可能还会涉及其他命名空间。如果您每个文件只保留一个命名空间(我想这是约定),那么通常没有真正的区别[但请参见Marc关于不同名称的不同类型在不同命名空间中发生冲突的评论]。如果使用StyleCop,则应将usings保留在命名空间内。


实际上,我记得可能会有差异……如果在不同层次上存在冲突类型等。 - Marc Gravell
作为另一个(更实际的)区别……其中一个可能会导致 LINQ-to-SQL 代码生成器崩溃,而另一个则不会。 ;-p - Marc Gravell

7
using语句放在namespace块内,可以将其作用域限制在该块中。这会影响许多事情。
  1. As @Steve Haigh mentioned, the using statement is only valid within the block, so if there were other namespace blocks, they wouldn't be affected.
  2. The namespace specified by the 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.
  3. Putting the 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());
                }
            }
        }

    The above code will compile, but it is unclear which Guid is being instantiated. If the using statement is inside of the namespace block, however, a compiler error is thrown.

请参阅相关的StyleCop文档以获取更完整的讨论。


+1。有趣的边缘情况。 - Steve

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接