1、使用where關鍵字限制類型參數函數
泛型約束spa |
描述code |
where T : structblog |
類型參數<T>的繼承鏈中必須有System.ValueType繼承 |
where T : class接口 |
類型參數<T>的繼承鏈中不容許有System.ValueType(例如<T>是一個引用類型)ci |
where T : new()table |
類型參數<T>必須有一個默認構造函數。若是同時有多個限制,這個限制必須放在最後。class |
where T : NameOfBaseClass基礎 |
類型參數<T>必須繼承至基類NameOfBaseClass |
where T : NameOfInterface |
類型參數<T>必須實現接口NameOfInterface |
爲了便於理解,下面經過幾個例子來了解where的用法。雖然這都是太基礎的東西,看到之前的筆記順便copy過來了 //T必須具有一個默認構造函數 public class MyGenericClass<T> where T : new() {...} //T必須是一個具有默認構造函數的類,並且實現了IDrawable接口 public class MyGenericClass<T> where T : class, IDrawable, new() {...} //MyGenericClass繼承至MyBase類,實現了ISomeInterface接口; //類型參數T的繼承鏈中有System.ValueType public class MyGenericClass<T> : MyBase, ISomeInterface where T : struct {...} //類型參數K必須具有默認構造函數;類型參數T必須實現泛型接口IComparable<T> public class MyGenericClass<K, T> where K : new() where T : IComparable<T> {...}