C#筆記 – 命名空間
命名空間和程序集
-
using System.IO; using System.Text; public class Program { public static void Main() { FileStream fs = new FileStream(...); StringBuilder sb = new StringBuilder(); } } -
命名空間對相關的類型進行邏輯分組,使開發者更方便定位類型
-
對於編譯器,命名空間的作用就是為類型名稱附加以句點分隔的符號,使之更可能具有唯一性
- 如上例中,編譯器將對FileStream的引用解析為System.IO.FileStream
-
編譯器在編譯源代碼時,需要保證調用的方法和類型是確實存在的
-
如果在源代碼文件或引用的程序集中找不到具有指定名稱的類型,就會嘗試在類型名稱前附加using指定的命名空間前綴。如果加上第一個(System.IO)後找不到,那就使用第二/三/…個代替並查找
-
查找到對應的類型後,編譯器就會自動將引用展開成:System.IO.FileStream和System.Text.StringBuilder
-
-
如果using的不同命名空間之間,有同名的類型,就需要在同名類型使用時,指出想使用的具體是哪個命名空間中的類型。
-
namespace A { public class Hello{ } } namespace B { public class Hello{ } } //////////////////////////////////// using A; using B; public class Program { public static void Main() { A.Hello a_Hello = new A.Hello(); B.Hello b_Hello = new B.Hello(); } } -
另一種方法是為類型或命名空間創建別名
-
限定的命名空間別名
-
using WinForms = System.Windows.Forms //A class WinForms { } //B class Test { static void Main() { Console.WriteLine(typeof(WinForms.Button)); //B Console.WriteLine(typeof(WinForms::Button)); //A } }
-
-
全局命名空間別名
-
class Configuration {} //A namespace Chapter7 { class Configuration { } //B class Test { static void Main() { Console.WriteLine(typeof(Configuration)); //B Console.WriteLine(typeof(global::Configuration)); //A } } }
-
-
外部別名
-
extern alias TestAlias;
-
-
-
-
如果命名空間名、類型名都一樣,就應用使用外部別名
-
命名空間和程序集的關係
-
兩者不一定相關
-
同一namespace中的類型可在不同的程序集中實現,如System.IO.FileStream在MSCorLib.dll;System.IO.FileSystemWatcher在System.dll
-
同一程序集可包含不同namespace的類型,如System.Int32和System.Text.StringBuilder都在MSCorLib.dll中
-
參考書目
- 《CLR via C#》(第4版) Jeffrey Richter
- 《深入理解C#》(第3版) Jon Skeet