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

 

在MSDN詳細說明:http://msdn.microsoft.com/zh-cn/library/bb384067.aspx


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM