C# 泛型
Where T:class 泛型類型約束
對于一個定義泛型類型為參數的函數,如果調用時傳入的對象為T對象或者為T的子類,在函數體內部如果需要使用T的屬性的方法時,我們可以給這個泛型增加約束;
//父類子類的定義 public class ProductEntryInfo { [Description("商品編號")] public int ProductSysNo { get; set; } //more } public class ProductEntryInfoEx : ProductEntryInfo { [Description("成份")] public string Component { get; set; } //more } //方法: private static string CreateFile<T>(List<T> list) where T:ProductEntryInfo { int productSysNo =list[0].ProductSysNo } //調用: List<ProductEntryInfo> peList = new List<ProductEntryInfo>(); string fileName = CreateFile( peList); List<ProductEntryInfoEx> checkListAll = new List<ProductEntryInfoEx>(); string fileNameEx = CreateFile(checkListAll);
這樣就可以實現上邊的CreateFile方法了
這樣類型參數約束,.NET支持的類型參數約束有以下五種:
where T : struct T必須是一個結構類型
where T : class T必須是一個類(class)類型
where T : new() T必須要有一個無參構造函數
where T : NameOfBaseClass | T必須繼承名為NameOfBaseClass的類
where T : NameOfInterface | T必須實現名為NameOfInterface的接口
分別提供不同類型的泛型約束。
可以提供類似以下約束
class MyClass<T, U>
where T : class
where U : struct
{ }
泛型初始化
default(T)
default(T)可以得到該類型的默認值。
C#在類初始化時,會給未顯示賦值的字段、屬性賦上默認值,但是值變量卻不會。值變量可以使用默認構造函數賦值,或者使用default(T)賦值。
默認構造函數是通過 new 運算符來調用的,如下所示:
- int myInt = new int();
default(T)如下所示:
- int myInt = default(int);
以上語句同下列語句效果相同:
- int myInt = 0;
請記住:在 C# 中不允許使用未初始化的變量。
之所以會用到default關鍵字,是因為需要在不知道類型參數為值類型還是引用類型的情況下,為對象實例賦初值。考慮以下代碼:
class TestDefault<T> { public T foo() { T t = null; //??? return t; } }
如果我們用int型來綁定泛型參數,那么T就是int型,那么注釋的那一行就變成了 int t = null;顯然這是無意義的。為了解決這一問題,引入了default關鍵字:
class TestDefault<T> { public T foo() { return default(T); } }

浙公網安備 33010602011771號