命名空間 為 .NET 型別提供邏輯分組機制,避免名稱衝突、提升可發現性、支援大型專案架構演進。雖然語法簡單,但其編譯時期解析規則、巢狀語意、using 指示詞優先順序、別名範圍等細節,深刻影響程式碼組織與維護成本。本章系統剖析命名空間核心機制與最佳實踐。
namespace MyCompany.Products
{
// 命名空間主體:型別定義 (class, struct, interface, enum, delegate)
public class Product { }
public enum Category { Electronics, Clothing }
}
namespace MyCompany.Products.Inventory
{
public class StockItem { }
}
namespace MyCompany
{
namespace Products
{
namespace Inventory
{
public class StockItem { }
}
}
}
兩者編譯後**完全相同**,型別完整名稱皆為 `MyCompany.Products.Inventory.StockItem`。寫法一簡潔,寫法二利於在同一檔案定義多個相關命名空間或加入 `using` 範圍限制。
// C# 10+ 單檔案單一命名空間簡潔語法
namespace MyCompany.Products.Inventory;
public class StockItem { }
public class Warehouse { }
using System;
using System.Collections.Generic;
using MyCompany.Products.Inventory;
// 之後可直接使用型別簡短名稱
var list = new List();
using static System.Console;
using static System.Math;
using static MyCompany.MathLib.MathExtensions;
WriteLine("Hello"); // Console.WriteLine
var r = Sqrt(2); // Math.Sqrt
var isEven = 4.IsEven(); // MathExtensions.IsEven
// 型別別名
using CustList = System.Collections.Generic.List;
using Json = System.Text.Json.JsonSerializer;
// 命名空間別名
using Prj = MyCompany.Products.Inventory;
using Legacy = OldSystem.DataAccess;
// 使用
var customers = new CustList();
var json = Json.Serialize(obj);
var item = new Prj.StockItem();
var repo = new Legacy.Repository();
// 解決同名型別衝突
using MyConfig = MyCompany.Configuration.Settings;
using ThirdPartyConfig = ThirdParty.Lib.Configuration.Settings;
// 指向泛型封閉型別
using IntDict = System.Collections.Generic.Dictionary;
using StringTask = System.Threading.Tasks.Task;
// C# 12+ 別名任意型別 (含 Tuple, Function Pointer 等)
using Point = (int X, int Y);
using Callback = delegate*;
using System; // 範圍:整個檔案 (或命名空間區塊)
namespace Outer
{
using System.IO; // 範圍:Outer 命名空間區塊內
namespace Inner
{
// 可見:System, System.IO, Outer 定義的型別
using Alias = System.Text.StringBuilder; // 範圍:Inner 區塊
}
// 此處不可見 Alias、System.IO (若未在 Outer 宣告)
}
// GlobalUsings.cs (專案任意位置,建議集中管理)
global using System;
global using System.Collections.Generic;
global using System.Linq;
global using System.Threading.Tasks;
global using MyCompany.Core; // 專案共用核心命名空間
<PropertyGroup>
<ImplicitUsings>enable</ImplicitUsings> <!-- 預設開啟 -->
</PropertyGroup>
CompanyName.ProductName[.Feature][.SubFeature]
// 範例
MyCompany.ECommerce
MyCompany.ECommerce.Orders
MyCompany.ECommerce.Orders.Pricing
MyCompany.ECommerce.Inventory.Management
| 原則 | 說明 | 反例 |
|---|---|---|
| 功能內聚 | 相關型別群組在一起 | 所有型別塞在 `MyCompany.Common` |
| 層次分明 | 核心/介面/實作/擴充分層 | 循環相依命名空間 |
| 公開面最小化 | 內部實作用 `internal`、子命名空間隔離 | 所有類別 `public` |
| 穩定依賴 | 高層不依賴低層細節,依賴抽象 | Domain 專案參考 Infrastructure 具體實作 |
命名空間是 .NET 類型組織的基石。掌握「檔案範圍命名空間」、「三種 using 模式」、「解析優先順序」、「global/隱含 using」現代機制,配合「功能內聚、層次分明、公開面最小化」設計原則,能構建清晰、可擴充、低耦合的專案架構。下一章將探討命名空間別名進階應用、跨組件類型轉發、`extern alias` 解決鑽石相依衝突等進階主題。