定義:在定義泛型的時候,咱們可使用 where 限制參數的範圍。數組
使用:在使用泛型的時候,你必須尊守 where 限制參數的範圍,不然編譯不會經過。函數
六種類型的約束:spa
T:類(類型參數必須是引用類型;這一點也適用於任何類、接口、委託或數組類型。)code
class MyClass<T, U> where T : class///約束T參數必須爲「引用 類型{ }」 where U : struct///約束U參數必須爲「值 類型」 { }
T:結構(類型參數必須是值類型。能夠指定除 Nullable 之外的任何值類型。)blog
class MyClass<T, U> where T : class///約束T參數必須爲「引用 類型{ }」 where U : struct///約束U參數必須爲「值 類型」 { }
T:new()(類型參數必須具備無參數的公共構造函數。當與其餘約束一塊兒使用時,new() 約束必須最後指定。)繼承
class EmployeeList<T> where T : Employee, IEmployee, System.IComparable<T>, new() { // ... }
T:<基類名>(類型參數必須是指定的基類或派生自指定的基類。)接口
public class Employee{} public class GenericList<T> where T : Employee
T:<接口名稱>(類型參數必須是指定的接口或實現指定的接口。能夠指定多個接口約束。約束接口也能夠是泛型的。)文檔
/// <summary> /// 接口 /// </summary> interface IMyInterface { } /// <summary> /// 定義的一個字典類型 /// </summary> /// <typeparam name="TKey"></typeparam> /// <typeparam name="TVal"></typeparam> class Dictionary<TKey, TVal> where TKey : IComparable, IEnumerable where TVal : IMyInterface { public void Add(TKey key, TVal val) { } }
T:U(爲 T 提供的類型參數必須是爲 U 提供的參數或派生自爲 U 提供的參數。也就是說T和U的參數必須同樣)it
class List<T> { void Add<U>(List<U> items) where U : T {/*...*/} }
1、可用於類:io
public class MyGenericClass<T> where T:IComparable { }
2、可用於方法:
public bool MyMethod<T>(T t) where T : IMyInterface { }
3、可用於委託:
delegate T MyDelegate<T>() where T : new()
在實際項目中何時用到它們?
有時候你在作一個項目的時候,你須要用到泛型,你只但願傳給你的泛型參數是限定範圍的,
好比你但願值類型,或者是引用類型,或者是繼承至某個類型、或者是符合某個接扣的類型,
這個時候你該如何辦?你就須要用到 WHERE 來限定了。
參考文檔:
https://msdn.microsoft.com/zh-cn/library/d5x73970.aspx
https://msdn.microsoft.com/zh-cn/library/bb384067.aspx