簡要來講泛型其實就是對類的抽象,是比類型更抽象的一級。對類來講,類是具備相同屬性和方法的一類對象的集合,也就是具備相同屬性的對象的抽象。數組
而泛型是具備相同執行指令的類型的集合,泛型是這些類似類型的一個模板,是對他們的更高一級的抽象。安全
舉例來講,如今有一個類,類中有一個某個類型的數組以及一個獲取數組某索引的值的一個方法。ide
代碼以下:this
public class MyGeneric_int { int[] arr; public void SetArr(int[] arr) { this.arr = arr; } public int GetValue(int index) { if (index<arr.Length) { return arr[index]; } else { throw new Exception("索引值超出了數組的界限"); } } }
若是咱們想要實現一個數組類型是string的,返回值也是string的方法,咱們必須在新建一個類,並複製代碼,而後更改數據類型,代碼以下:spa
public class MyGeneric_string { string[] arr; public void SetArr(string[] arr) { this.arr = arr; } public string GetValue(int index) { if (index<arr.Length) { return arr[index]; } else { throw new Exception("索引值超出了數組的界限"); } } }
若是再要求返回其餘類型的,咱們只能再新建類型並複製而後修改。。。3d
可是,有了泛型,一切就變的簡單多了,代碼以下:code
public class MyGeneric<T> { T[] arr; public void SetArr(T[] arr) { this.arr = arr; } public T GetValue(int index) { if (index<arr.Length) { return arr[index]; } else { throw new Exception("索引值超出了數組的界限"); } } }
咱們只需在申明泛型類指明類型,其餘一切都不用再修改,真是方便,快鍵,安全。對象
泛型類是某些具備相同執行指令的類的模板,它是類型的抽象或者集合。blog
(1)泛型類的申明索引
在普通類的類名後邊加尖括號,並添加類型佔位符(佔位符通常用T表示),如:
public class MyGeneric<T> { T[] arr; public void SetArr(T[] arr) { this.arr = arr; } public T GetValue(int index) { if (index<arr.Length) { return arr[index]; } else { throw new Exception("索引值超出了數組的界限"); } } }
(2)泛型類的使用
泛型類在實例化時,必須指定代替佔位符的具體類,如:
static void Main(string[] args) { MyGeneric<int> mygen = new MyGeneric<int>();//用int類型代替佔位符 mygen.SetArr(new int[] {1,2,3 }); int a=mygen.GetValue(1); MyGeneric<string> mygen2 = new MyGeneric<string>();//用string類型代替佔位符 mygen2.SetArr(new string[] {"1","2","3" }); string b = mygen2.GetValue(1); }
泛型方法的申明比普通方法的申明多了一對尖括號和泛型參數,例如:
public void MyGenericMethod<T>(T t)
若是有多個泛型模板,中間用「,」隔開,如:
public T MyGenericMethod<T,R>(T t,R r)
泛型方法的調用:咱們先申明一個沒有返回值的泛型方法:MyMethod
static void MyMethod<T>(T[] arr) { foreach (T item in arr) { Console.WriteLine(item.ToString()); } }
接着在main方法中調用:
static void Main(string[] args) { MyMethod<string>(new string[] {"1","2","3" });//泛型類型爲string MyMethod(new string[] { "1", "2", "3" }); //這個調用編譯器自動根據參數推斷類型 MyMethod<int>(new int[] { 1, 2, 3 }); MyMethod(new int[] {1,2,3}); }
泛型委託的申明方式和直接申明委託的方式就多了一對尖括號,形式是這樣的:
delegate R MyDelgate<T,R>(T t)
關鍵字說明:
delegate:申明委託的關鍵字
R:申明委託的返回類型
<T,R>:泛型委託的類型參數
T t :委託的形式參數
泛型委託實例:
public delegate void MyDel<T>(T t);//沒有返回類型的泛型委託 public delegate R MyDel<T,R>(T t); //有返回類型的委託