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
{ }