C# where子句
where 子句用於指定類型約束,這些約束可以作為泛型聲明中定義的型別參數的變數。 1.介面約束。 例如,可以聲明一個泛型類 MyGenericClass,這樣,型別參數 T 就可以實現 IComparable<T> 介面:public class MyGenericClass<T> where T:IComparable { } 2.基類約束:指出某個類型必須將指定的類作為基類(或者就是該類本身),才能用作該泛型型別的型別參數。 這樣的約束一經使用,就必須出現在該型別參數的所有其他約束之前。class MyClassy<T, U> where T : class where U : struct { } 3.where 子句還可以包括建構函式約束。 可以使用 new 運算子建立型別參數的執行個體;但型別參數為此必須受建構函式約束 new() 的約束。new() 約束可以讓編譯器知道:提供的任何型別參數都必須具有可訪問的無參數(或預設)建構函式。例如:public class MyGenericClass <T> where T: IComparable, new() { // The following line is not possible without new() constraint: T item = new T(); }
new() 約束出現在 where 子句的最後。 4.對於多個型別參數,每個型別參數都使用一個 where 子句, 例如:interface MyI { } class Dictionary<TKey,TVal> where TKey: IComparable, IEnumerable where TVal: MyI { public void Add(TKey key, TVal val) { } }
5.還可以將約束附加到泛型方法的型別參數,例如: public bool MyMethod<T>(T t) where T : IMyInterface { }
請注意,對於委託和方法兩者來說,描述型別參數約束的文法是一樣的: delegate T MyDelegate<T>() where T : new() |
Link from : http://hi.baidu.com/%D0%A6%D3%F0%BA%A8%CC%EC/blog/item/9701871c28d2fb13413417fd.html