2011-09-02 43 views
7

可能重复:
Should Usings be inside or outside the namespace'使用'应位于名称空间还是外部?

是否有喜欢这个

namespace Foo 
{ 
    using System; 
    using System.IO; 

,而不是默认的任何技术原因

using System; 
using System.IO; 

namespace Foo 
{ 
+1

请参阅http://stackoverflow.com/questions/125319/should-usings-be-inside-or-outside-the-namespace – chrisaut

+0

它可以同时工作,但通常人们更喜欢它在命名空间之外,但是您可能会看到这个[在命名空间或外部使用](http://stackoverflow.com/questions/125319/should-usings-be-inside-or-outside-the-namespace) –

回答

7

Eric Lippert explains this

一般而言,它们是相同的。
但是,名称空间中的using语句可以看到名称空间外部包含的名称空间和别名。

0

没有技术原因,只是一个偏好。尽管如此,第二部分代码看起来更干净。

2

几乎*这两者之间的唯一区别是,如果您在同一个文件中使用了多个命名空间(或者您多次使用同一个命名空间)。我不确定你为什么要这样做,你当然可以:

using System; 

namespace FooNamespace 
{ 
    using System.IO; 

    class Foo 
    { 
     // you can use types from System and System.IO directly here 
    } 
} 

namespace BarNamespace 
{ 
    class Bar 
    { 
     // you can't use types from System.IO directly here 
     // but you can use types from System 
    } 
} 

*请参阅SLaks的答案。

+0

这对扩展方法很有用。 http://blog.slaks.net/2011/07/creating-local-extension-methods.html – SLaks

相关问题