C#泛型約束的深入理解
更新時間:2013年05月31日 11:32:16 作者:
本篇文章是對C#中的泛型約束進行了詳細的分析介紹,需要的朋友參考下
where 子句用于指定類型約束,這些約束可以作為泛型聲明中定義的類型參數(shù)的變量。
1.接口約束。
例如,可以聲明一個泛型類 MyGenericClass,這樣,類型參數(shù) T 就可以實現(xiàn) IComparable<T> 接口:
public class MyGenericClass<T> where T:IComparable { }
2.基類約束:指出某個類型必須將指定的類作為基類(或者就是該類本身),才能用作該泛型類型的類型參數(shù)。
這樣的約束一經(jīng)使用,就必須出現(xiàn)在該類型參數(shù)的所有其他約束之前。
class MyClassy<T, U>
where T : class
where U : struct
{
}
3.where 子句還可以包括構造函數(shù)約束。
可以使用 new 運算符創(chuàng)建類型參數(shù)的實例;但類型參數(shù)為此必須受構造函數(shù)約束 new() 的約束。new() 約束可以讓編譯器知道:提供的任何類型參數(shù)都必須具有可訪問的無參數(shù)(或默認)構造函數(shù)。例如:
public class MyGenericClass <T> where T: IComparable, new()
{
// The following line is not possible without new() constraint:
T item = new T();
}
new() 約束出現(xiàn)在 where 子句的最后。
4.對于多個類型參數(shù),每個類型參數(shù)都使用一個 where 子句
例如:
interface MyI { }
class Dictionary<TKey,TVal>
where TKey: IComparable, IEnumerable
where TVal: MyI
{
public void Add(TKey key, TVal val)
{
}
}
5.還可以將約束附加到泛型方法的類型參數(shù),例如:
public bool MyMethod<T>(T t) where T : IMyInterface { }
請注意,對于委托和方法兩者來說,描述類型參數(shù)約束的語法是一樣的:
delegate T MyDelegate<T>() where T : new()
1.接口約束。
例如,可以聲明一個泛型類 MyGenericClass,這樣,類型參數(shù) T 就可以實現(xiàn) IComparable<T> 接口:
復制代碼 代碼如下:
public class MyGenericClass<T> where T:IComparable { }
2.基類約束:指出某個類型必須將指定的類作為基類(或者就是該類本身),才能用作該泛型類型的類型參數(shù)。
這樣的約束一經(jīng)使用,就必須出現(xiàn)在該類型參數(shù)的所有其他約束之前。
復制代碼 代碼如下:
class MyClassy<T, U>
where T : class
where U : struct
{
}
3.where 子句還可以包括構造函數(shù)約束。
可以使用 new 運算符創(chuàng)建類型參數(shù)的實例;但類型參數(shù)為此必須受構造函數(shù)約束 new() 的約束。new() 約束可以讓編譯器知道:提供的任何類型參數(shù)都必須具有可訪問的無參數(shù)(或默認)構造函數(shù)。例如:
復制代碼 代碼如下:
public class MyGenericClass <T> where T: IComparable, new()
{
// The following line is not possible without new() constraint:
T item = new T();
}
new() 約束出現(xiàn)在 where 子句的最后。
4.對于多個類型參數(shù),每個類型參數(shù)都使用一個 where 子句
例如:
復制代碼 代碼如下:
interface MyI { }
class Dictionary<TKey,TVal>
where TKey: IComparable, IEnumerable
where TVal: MyI
{
public void Add(TKey key, TVal val)
{
}
}
5.還可以將約束附加到泛型方法的類型參數(shù),例如:
復制代碼 代碼如下:
public bool MyMethod<T>(T t) where T : IMyInterface { }
請注意,對于委托和方法兩者來說,描述類型參數(shù)約束的語法是一樣的:
復制代碼 代碼如下:
delegate T MyDelegate<T>() where T : new()
相關文章
C#中IDispose接口的實現(xiàn)及為何這么實現(xiàn)詳解
這篇文章主要給大家介紹了關于C#中IDispose接口的實現(xiàn)及為何這么實現(xiàn)的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2018-05-05