[C#] 泛型的條件約束 Constraints

  • 21932
  • 0
  • 2011-03-10

[C#] 泛型的條件約束 Constraints

前篇介紹了 泛用方法,接下來再筆記一下條件約束。

條件約束有三種:型別條件約束、New 條件約束、限制參考型別或是數值型別的條件約束

 

型別條件約束

若是需要限制某個型別參數是繼承某一個類別或是實作一或多個介面。


<KeyType,ElementType>
where KeyType : IComparable
where ElementType : System.Web.UI.WebControls.WebControl
{
	...
}

//編譯發生錯誤
MyGenericCollection<int,double> row1;

//編譯正常
MyGenericCollection<int,System.Web.UI.WebControls.Label> row1;

 

New 條件約束

有時候我們會使用泛用類別工廠,他使用傳遞進來之型別數的型別來建立一個執行個體;

為了確保傳進來的擁有一個建構函式,也確保不是 MustInherit 類別與介面。


	T CreateInstance(){
		T newInstance = new T();
		...
		return  newInstance;
	}
}

 

 

限制參考型別或是數值型別的條件約束

若要將傳遞的型別參數必須是「參考型別」,則須加入 class 關鍵字;

若要將傳遞的型別參數必須是「實數型別」,則須加入 struct 關鍵字。


	...
}

public class MyClass<T> where T : struct{
	...
}

如何指定多個條件約束


where T : class,IComparable,IDisposable,new(){
	...
}

利用型別參數的物件存取類別與條件約束類別的成員


interface IRun{
	void A();
	void B();
}

//這是使用者自訂介面
interface IMove{
	void A();
	void B();
}

//使用者自訂類別
class Car(){
	public void E();
}

// 自訂泛用類別
class MyClass<T1,T2>
	where T1 : Car,IRun,new()
	where T2 : IRun,IMove,new(){
	
	void test(){
		//建立一個型別為 T1 的物件
		T1 obj1 = new T1();

		//T1擁有類別條件約束 Car,
		//所以可以直接存取Car 的成員E
		obj1.E();

		//T1 擁有介面條件約束 IRun,
		//所以可以直接存取 IRun 的成員
		obj1.A();

		//建立一個型別為 T2  物件
		T2 obj2 = new T2();

		//編譯錯誤,由於介面 IRun 與 IMove 
		//都擁有一個名稱為 A 的成員,所以
		//這樣用會造成錯誤
		obj2.A();

		//若要避免錯誤,須轉型
		((IRun)obj2).A();
	}
}

型別參數的多載



}

public class MyCollection<T1>{
	static void Test(MyCollection<T1> arg){
		
	}
	...
}

pubic class MyColleciton<T1,T2>{
	public static void Show(MyColleciton<T1,T2>[] args){

	}
	...
}

MyCollection o1;

MyCollection<int> o2;

MyCollection<int,string> o3;

//參考 2 個型別參數
MyCollection<int,DateTime>.Show(null);

 

定義不同型別參數來多載泛用方法


	static int Compare<T>(T arg1,T arg2){
	}
	sataic int Compare<T1,T2>(T1 arg2,T2 arg2){
	}
}
...
MyClass.Compare<int>(1,2);
MyClass.Compare<int,string>(10,"test");

HEMiDEMi 的標籤:

三小俠  小弟獻醜,歡迎指教