首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 2.0 泛型類別建立與使用 (3) - 泛型方法定義與型別約束

     編輯:關於C語言

六、定義泛型方法

將 Customer 替換為型別參數 T,完成輕量級泛型清單類別:

public class List<T> : CollectionBase
{
    public T this[int index]
    {
        get { return (T)List[index]; }
        set { List[index] = value; }
    }
    public int Add(T value) { return List.Add(value); }
}

七、增加型別約束

語法:where T : constraint_type。例如要求實作 IDisposable 以配合 using 區塊:

public class List<T> : CollectionBase where T : IDisposable
{
    // ...
}

約束類型可為:類別、介面、結構、無參公用建構函式 (new())、特定基底類別。

八、總結

泛型設計目的:減少重複實作,僅變更資料型別。抽象資料結構 (佇列、堆疊、清單) 最適合泛型化。善用 System.Collections.Generic 現有泛型類別,轉換新資料結構為可重用泛型程式碼元素。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved