C# 2.0 引入泛型,是語言演進的里程碑。本文整理自官方文件翻譯,深入解析「泛型型別具現化」與「型別參數約束」兩大核心機制,幫助開發者理解編譯器與 CLR 背後的運作細節。
Stack<int>)時,JIT 將 IL 具現化為原生碼,以實際型別取代參數。Stack<int>、Stack<long>)各自擁有獨立原生碼副本,因大小/配置不同。Stack<string>、Stack<object>)共享單一原生碼,因參考在原生層級皆為指標,大小相同。預設型別參數 T 僅能存取 object 成員(Equals、GetHashCode、ToString)。若需呼叫 CompareTo,需約束 T : IComparable。
public class Dictionary<K, V> where K : IComparable
{
public void Add(K key, V value)
{
if (key.CompareTo(someKey) < 0) { ... } // 合法,K 保證有 CompareTo
}
}
| 約束 | 說明 |
|---|---|
where T : ClassName | 基底類別約束(單一) |
where T : InterfaceName | 介面約束(可多個) |
where T : new() | 建構函式約束:需有公用無參數建構子 |
where T : struct | 值型別約束 |
where T : class | 參考型別約束 |
where T : unmanaged | 非受控型別約束 |
where T : notnull | 非 Nullable 型別約束 |
where T : default | 預設約束(覆寫時使用) |
public class EntityTable<K, E>
where K : IComparable<K>, IPersistable
where E : Entity, new()
{
public void Add(K key, E entity)
{
if (key.CompareTo(other) < 0) { ... } // K 滿足 IComparable
var newEntity = new E(); // E 滿足 new()
}
}
List<T> where T : IComparable 會排除不實作 IComparable 的型別,即使永遠不呼叫 Sort()。泛型具現化機制讓 C# 兼具型別安全與執行效能;約束機制則在靈活性與安全性間取得平衡。理解 JIT 對值/參考型別的不同處理,有助於設計高效能泛型程式庫。