天天看點

C#入門經典第十二章

第12章   泛型(C++的模闆)

12.1泛型的概念

在C++中,編譯器可以檢測出在哪裡使用了模闆的某個特定類型,例如,模闆B的A類型,然後編譯需要的代碼,來建立這個類型。而在C#中,所有的操作都在運作期間進行。

12.2使用泛型

12.2.1可空類型(nullabletype)

System.Nullable<type>,null,HasValue

System.Nullable<type>=type?

1.  運算符和可空類型

2.  ??空接合運算符(nullcoalescing operator),

Op1??op2; op1==null?op1:op2;

12.2.2 System.Collections.Generic名稱空間

     1.List<T>

     List<T>myCollection=new List<T>();

     CollectionBase主要用于向後相容,使用CollectionBase的唯一場合是更多的控制向類的使用者展示的成員。

2.對泛型清單進行排序和搜尋

使用泛型接口IComparer<T>和Icomparable<T>

System.Text.StringBuilder:Append(),AppendFormat(),ToString();

Comparison<T>:這個委托類型用于排序方法,其傳回類型和參數是int method(T objectA,T obejct B);

Predicate<T>:這個委托類型用于搜尋方法,其傳回類型和參數是bool method(T targetObject);

3.  Dictionary<K,V>

Dictionary<keyType,valType>things=new Dictionary<keyType,valType>();

Foreach(keyType key in type.Keys)

{}

Foreach(valType key in type.Values)

{}

Foreach(KeyValuePair<keyType,valType>thing in things)

{}

Dictionary<K,V>允許把IComparer<K>接口傳遞給其構造函數。?

IComparer<T>,IComparable<T>比較

12.3定義泛型

12.3.1定義泛型類

Class MyGenericCLass<T>

{

}

不知道T的類型,在類的定義中不能使用它的構造函數,不能使用new T();

1.default關鍵字:引用null,值:預設值。

innerT1Object=default(T1);

2.限制類型:限制泛型中可使用的資料類型

     WhereT1:constraint1

3.從泛型類中繼承

     繼承類型封閉,非泛型類繼承泛型類,要明确泛型類中的所有類型參數。

4.泛型運算符

     Publicstatic implicit operator List<Animal>(Farm<T> farm)

{}

5.泛型結構

12.3.2定義泛型接口

     InterfaceMyFarmingInterface<T>

     WhereT:Animal

{}

12.3.3定義泛型方法

Public T GetDeafult<T>()

{

Return default(T);

}

12.3.4定義泛型委托

Public delegate T1MyDelegate<tT1,T2>(T2 op1,T2 op2) where T1:T2;