2011-09-02 46 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

相關問題