.NET namespaces and using statements

.NET namespaces and using statements

不再见 发布于 2021-11-25 字数 404 浏览 798 回复 2 原文

Possible Duplicate:
Should Usings be inside or outside the namespace

What is the difference between

namespace x
{
  using y;
}

and

using y;
namespace x
{
}

?

如果你对这篇文章有疑问,欢迎到本站 社区 发帖提问或使用手Q扫描下方二维码加群参与讨论,获取更多帮助。

扫码加入群聊

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

秋千易 2022-06-07 2 楼

Putting the using statement inside the namespace block scopes it to that block. This affects a number of things.

  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.

See the related StyleCop documentation for a more complete discussion.

梦旅人picnic 2022-06-07 1 楼

The first one has y in scope for just the namespace x, the second has y in scope for the whole file, so potentialy other namespaces. If you keep to one namespace per file (I'd guess that was the convention) then there's usually no real difference [but see Marc's comment about clashes if different types have the same name in different namespaces]. If you use StyleCop it will want you to keep the usings inside the namespace.