StandardClass a = new StandardClass();
StandardClass b = new StandardClass();
StandardClass c = new StandardClass();
// CLR 中僅存在一個 StandardClass 類型物件
// 靜態欄位 _count 共享,最終值為 3
GenericClass gA = new GenericClass();
GenericClass gB = new GenericClass();
GenericClass gC = new GenericClass();
GenericClass gD = new GenericClass();
// CLR 產生三個獨立類型:
// GenericClass`1[Boolean], GenericClass`1[Int32], GenericClass`1[String]
// 各自擁有獨立靜態欄位 _count
// gC/gD 共享 GenericClass`1[String] 類型,_count 為 2
// 非泛型
There are 1 instances of StandardClass which contains 0 items of type System.Object[]...
There are 2 instances of StandardClass which contains 0 items of type System.Object[]...
There are 3 instances of StandardClass which contains 0 items of type System.Object[]...
// 泛型
There are 1 instances of GenericClass`1[System.Boolean] which contains 0 items of type System.Boolean[]...
There are 1 instances of GenericClass`1[System.Int32] which contains 0 items of type System.Int32[]...
There are 1 instances of GenericClass`1[System.String] which contains 0 items of type System.String[]...
There are 2 instances of GenericClass`1[System.String] which contains 0 items of type System.String[]...
// 非泛型:編譯通過,執行時可能出錯
StandardClass c = new StandardClass(5);
c.AddItem("str");
c.AddItem(123); // 裝箱,無編譯錯誤
// 泛型:編譯期攔截
GenericClass g = new GenericClass(5);
g.AddItem("str");
g.AddItem(123); // CS1503: 無法從 int 轉換為 string
box/unbox IL 指令GetItem 直接回傳 T,無需 castclass大量實值型別參數化會產生大量機器碼。對策:
where T : IComparable<T>)