.net:名称空间:在名称空间之前或之后编写USING指令的确切区别是什么 [英] .net : namespace : what is exact difference in writing USING directives before or after namespace

查看:83
本文介绍了.net:名称空间:在名称空间之前或之后编写USING指令的确切区别是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
应该在命名空间之内还是之外使用
.NET名称空间和使用语句

Possible Duplicate:
Should Usings be inside or outside the namespace
.NET namespaces and using statements

在命名空间声明之前或之后编写USING指令的确切区别是什么.

What is exact difference in writing USING directives before or after namespace declaration.

示例:

using System;
using System.Linq;
using NUnit.Framework;

namespace HostTest
{
 /**  code goes here **/
}

namespace HostService
{
  using System.Runtime.Serialization;
  using System;

       /**  code goes here **/
}

推荐答案

Darin的回答是正确的,但并不全面-因为这也对using指令本身执行查找的方式有所不同:它们是否尝试匹配另一个命名空间中的名称

Darin's answer is correct but not comprehensive - because it also makes a difference to how the using directives themselves perform lookup: whether they attempt to match the names within another namespace.

埃里克·利珀特(Eric Lippert)有一个很棒的博客发布以了解更多详细信息.在我看来,最重要的一点是最后:

Eric Lippert has a great blog post going into more details. To my mind, the most important point is at the end:

因此,我的建议是:

Therefore my advice is now:

  • 每个文件只有一个顶级名称空间
  • 如果您选择在空间中使用指令,然后使用全局别名限定符对它们进行完全限定

作为推论,我建议第二点意味着,在名称空间内使用指令比在名称空间外使用指令更难正确,因此我将其放置在外部.这也是Visual Studio的默认设置:)

As a corollary, I'd suggest that as the second point means that using directives inside namespaces are trickier to get right than using directives outside namespaces, I'd go with putting them outside. It also helps that that's the Visual Studio default :)

尽管这只是一个编译时问题-它只会影响编译器查找名称的方式,而不会影响使用这些名称生成的代码的外观.

This is all just a compile-time issue though - it only affects how the compiler looks up names, not what the generated code using those names looks like.

术语的最后一点:您的问题谈论的是using 声明,但所有这些都是using 指令. using语句是获取资源并将其处置的语句:

One final point of terminology: your question talks about using statements, but all of these are using directives. The using statement is the one that acquires a resource and disposes of it at the end:

using (Stream stream = ...)
{
    // ...
}

我仅本着进修的精神提起这件事-在这种特殊情况下,你的意思很明显:)

I mention this only in the spirit of further education - it was obvious what you meant in this particular case :)

这篇关于.net:名称空间:在名称空间之前或之后编写USING指令的确切区别是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆