一、泛型:
所謂泛型,即通過參數化類型來實現在同一份代碼上操作多種數據類型。泛型編程是一種編程范式,它利用“參數化類型”將類型抽象化,從而實現更為靈活的復用。
二、泛型約束:
轉自:http://www.cnblogs.com/kk888/archive/2011/09/01/2161647.html
在定義泛型類時,可以對客戶端代碼能夠在實例化類時用於類型參數的類型種類施加限制。如果客戶端代碼嘗試使用某個約束所不允許的類型來實例化類,則會產生編譯時錯誤。這些限制稱為約束。約束是使用 where 上下文關鍵字指定的。
下表列出了五種類型的約束:
約束 | 說明 |
---|---|
T:struct |
類型參數必須是值類型。可以指定除 Nullable 以外的任何值類型。 |
T:class |
類型參數必須是引用類型,包括任何類、接口、委托或數組類型。 |
T:new() |
類型參數必須具有無參數的公共構造函數。當與其他約束一起使用時,new() 約束必須最后指定。 |
T:<基類名> |
類型參數必須是指定的基類或派生自指定的基類。 |
T:<接口名稱> |
類型參數必須是指定的接口或實現指定的接口。可以指定多個接口約束。約束接口也可以是泛型的。 |
T:U |
為 T 提供的類型參數必須是為 U 提供的參數或派生自為 U 提供的參數。這稱為裸類型約束. |
---------------------------------------
一.派生約束
1.常見的
public class MyClass5<T> where T :IComparable { }
2.約束放在類的實際派生之后
public class B { } public class MyClass6<T> : B where T : IComparable { }
3.可以繼承一個基類和多個接口,且基類在接口前面
public class B { } public class MyClass7<T> where T : B, IComparable, ICloneable { }
二.構造函數約束
1.常見的
public class MyClass8<T> where T : new() { }
2.可以將構造函數約束和派生約束組合起來,前提是構造函數約束出現在約束列表的最后
public class MyClass8<T> where T : IComparable, new() { }
三.值約束
1.常見的
public class MyClass9<T> where T : struct { }
2.與接口約束同時使用,在最前面(不能與基類約束,構造函數約束一起使用)
public class MyClass11<T> where T : struct, IComparable { }
四.引用約束
1.常見的
public class MyClass10<T> where T : class { }
五.多個泛型參數
public class MyClass12<T, U> where T : IComparable where U : class { }
六.繼承和泛型
public class B<T>{ }
1. 在從泛型基類派生時,可以提供類型實參,而不是基類泛型參數
public class SubClass11 : B<int> { }
2.如果子類是泛型,而非具體的類型實參,則可以使用子類泛型參數作為泛型基類的指定類型
public class SubClass12<R> : B<R> { }
3.在子類重復基類的約束(在使用子類泛型參數時,必須在子類級別重復在基類級別規定的任何約束)
public class B<T> where T : ISomeInterface { } public class SubClass2<T> : B<T> where T : ISomeInterface { }
4.構造函數約束
public class B<T> where T : new() { public T SomeMethod() { return new T(); } } public class SubClass3<T> : B<T> where T : new(){ }