這篇文章主要講解C#中的泛型,泛型在C#中有很重要的地位,尤爲是在搭建項目框架的時候。編程
1、什麼是泛型數組
泛型是C#2.0推出的新語法,不是語法糖,而是2.0由框架升級提供的功能。緩存
咱們在編程程序時,常常會遇到功能很是類似的模塊,只是它們處理的數據不同。但咱們沒有辦法,只能分別寫多個方法來處理不一樣的數據類型。這個時候,那麼問題來了,有沒有一種辦法,用同一個方法來處理傳入不一樣種類型參數的辦法呢?泛型的出現就是專門來解決這個問題的。安全
2、爲何使用泛型架構
先來看下面一個例子:框架
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MyGeneric { public class CommonMethod { /// <summary> /// 打印個int值 /// /// 由於方法聲明的時候,寫死了參數類型 /// 已婚的男人 Eleven San /// </summary> /// <param name="iParameter"></param> public static void ShowInt(int iParameter) { Console.WriteLine("This is {0},parameter={1},type={2}", typeof(CommonMethod).Name, iParameter.GetType().Name, iParameter); } /// <summary> /// 打印個string值 /// </summary> /// <param name="sParameter"></param> public static void ShowString(string sParameter) { Console.WriteLine("This is {0},parameter={1},type={2}", typeof(CommonMethod).Name, sParameter.GetType().Name, sParameter); } /// <summary> /// 打印個DateTime值 /// </summary> /// <param name="oParameter"></param> public static void ShowDateTime(DateTime dtParameter) { Console.WriteLine("This is {0},parameter={1},type={2}", typeof(CommonMethod).Name, dtParameter.GetType().Name, dtParameter); } } }
結果:分佈式
從上面的結果中咱們能夠看出這三個方法,除了傳入的參數不一樣外,其裏面實現的功能都是同樣的。在1.0版的時候,尚未泛型這個概念,那麼怎麼辦呢。相信不少人會想到了OOP三大特性之一的繼承,咱們知道,C#語言中,object是全部類型的基類,將上面的代碼進行如下優化:ide
public static void ShowObject(object oParameter) { Console.WriteLine("This is {0},parameter={1},type={2}", typeof(CommonMethod), oParameter.GetType().Name, oParameter); }
結果:函數
從上面的結果中咱們能夠看出,使用Object類型達到了咱們的要求,解決了代碼的可複用。可能有人會問定義的是object類型的,爲何能夠傳入int、string等類型呢?緣由有二:性能
一、object類型是一切類型的父類。
二、經過繼承,子類擁有父類的一切屬性和行爲,任何父類出現的地方,均可以用子類來代替。
可是上面object類型的方法又會帶來另一個問題:裝箱和拆箱,會損耗程序的性能。
微軟在C#2.0的時候推出了泛型,能夠很好的解決上面的問題。
3、泛型類型參數
在泛型類型或方法定義中,類型參數是在其實例化泛型類型的一個變量時,客戶端指定的特定類型的佔位符。 泛型類( GenericList<T>
)沒法按原樣使用,由於它不是真正的類型;它更像是類型的藍圖。 若要使用 GenericList<T>
,客戶端代碼必須經過指定尖括號內的類型參數來聲明並實例化構造類型。 此特定類的類型參數能夠是編譯器可識別的任何類型。 可建立任意數量的構造類型實例,其中每一個使用不一樣的類型參數。
上面例子中的代碼能夠修改以下:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace MyGeneric 8 { 9 public class GenericMethod 10 { 11 /// <summary> 12 /// 泛型方法 13 /// </summary> 14 /// <typeparam name="T"></typeparam> 15 /// <param name="tParameter"></param> 16 public static void Show<T>(T tParameter) 17 { 18 Console.WriteLine("This is {0},parameter={1},type={2}", 19 typeof(GenericMethod), tParameter.GetType().Name, tParameter.ToString()); 20 } 21 } 22 }
調用:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MyGeneric { class Program { static void Main(string[] args) { int iValue = 123; string sValue = "456"; DateTime dtValue = DateTime.Now; Console.WriteLine("***********CommonMethod***************"); CommonMethod.ShowInt(iValue); CommonMethod.ShowString(sValue); CommonMethod.ShowDateTime(dtValue); Console.WriteLine("***********Object***************"); CommonMethod.ShowObject(iValue); CommonMethod.ShowObject(sValue); CommonMethod.ShowObject(dtValue); Console.WriteLine("***********Generic***************"); GenericMethod.Show<int>(iValue); GenericMethod.Show<string>(sValue); GenericMethod.Show<DateTime>(dtValue); Console.ReadKey(); } } }
顯示結果:
爲何泛型能夠解決上面的問題呢?
泛型是延遲聲明的:即定義的時候沒有指定具體的參數類型,把參數類型的聲明推遲到了調用的時候才指定參數類型。 延遲思想在程序架構設計的時候很受歡迎。例如:分佈式緩存隊列、EF的延遲加載等等。
泛型到底是如何工做的呢?
控制檯程序最終會編譯成一個exe程序,exe被點擊的時候,會通過JIT(即時編譯器)的編譯,最終生成二進制代碼,才能被計算機執行。泛型加入到語法之後,VS自帶的編譯器又作了升級,升級以後編譯時遇到泛型,會作特殊的處理:生成佔位符。再次通過JIT編譯的時候,會把上面編譯生成的佔位符替換成具體的數據類型。請看下面一個例子:
1 Console.WriteLine(typeof(List<>)); 2 Console.WriteLine(typeof(Dictionary<,>));
結果:
從上面的截圖中能夠看出:泛型在編譯以後會生成佔位符。
注意:佔位符須要在英文輸入法狀態下才能輸入,只須要按一次波浪線(數字1左邊的鍵位)的鍵位便可,不須要按Shift鍵。
一、泛型性能問題
請看一下的一個例子,比較普通方法、Object參數類型的方法、泛型方法的性能。
添加一個Monitor類,讓三種方法執行一樣的操做,比較用時長短:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace MyGeneric 8 { 9 public class Monitor 10 { 11 public static void Show() 12 { 13 Console.WriteLine("****************Monitor******************"); 14 { 15 int iValue = 12345; 16 long commonSecond = 0; 17 long objectSecond = 0; 18 long genericSecond = 0; 19 20 { 21 Stopwatch watch = new Stopwatch(); 22 watch.Start(); 23 for (int i = 0; i < 100000000; i++) 24 { 25 ShowInt(iValue); 26 } 27 watch.Stop(); 28 commonSecond = watch.ElapsedMilliseconds; 29 } 30 { 31 Stopwatch watch = new Stopwatch(); 32 watch.Start(); 33 for (int i = 0; i < 100000000; i++) 34 { 35 ShowObject(iValue); 36 } 37 watch.Stop(); 38 objectSecond = watch.ElapsedMilliseconds; 39 } 40 { 41 Stopwatch watch = new Stopwatch(); 42 watch.Start(); 43 for (int i = 0; i < 100000000; i++) 44 { 45 Show<int>(iValue); 46 } 47 watch.Stop(); 48 genericSecond = watch.ElapsedMilliseconds; 49 } 50 Console.WriteLine("commonSecond={0},objectSecond={1},genericSecond={2}" 51 , commonSecond, objectSecond, genericSecond); 52 } 53 } 54 55 #region PrivateMethod 56 private static void ShowInt(int iParameter) 57 { 58 //do nothing 59 } 60 private static void ShowObject(object oParameter) 61 { 62 //do nothing 63 } 64 private static void Show<T>(T tParameter) 65 { 66 //do nothing 67 } 68 #endregion 69 70 } 71 }
Main()方法調用:
1 Monitor.Show();
結果:
從結果中能夠看出:泛型方法的性能最高,其次是普通方法,object方法的性能最低。
4、泛型類
除了方法能夠是泛型之外,類也能夠是泛型的,例如:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace MyGeneric 8 { 9 /// <summary> 10 /// 泛型類 11 /// </summary> 12 /// <typeparam name="T"></typeparam> 13 public class GenericClass<T> 14 { 15 public T _T; 16 } 17 }
Main()方法中調用:
1 // T是int類型 2 GenericClass<int> genericInt = new GenericClass<int>(); 3 genericInt._T = 123; 4 // T是string類型 5 GenericClass<string> genericString = new GenericClass<string>(); 6 genericString._T = "123";
除了能夠有泛型類,也能夠有泛型接口,例如:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace MyGeneric 8 { 9 /// <summary> 10 /// 泛型接口 11 /// </summary> 12 public interface IGenericInterface<T> 13 { 14 //泛型類型的返回值 15 T GetT(T t); 16 } 17 }
也能夠有泛型委託:
1 public delegate void SayHi<T>(T t);//泛型委託
注意:
一、泛型在聲明的時候能夠不指定具體的類型,可是在使用的時候必須指定具體類型,例如:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace MyGeneric 8 { 9 /// <summary> 10 /// 使用泛型的時候必須指定具體類型, 11 /// 這裏的具體類型是int 12 /// </summary> 13 public class CommonClass :GenericClass<int> 14 { 15 } 16 }
若是子類也是泛型的,那麼繼承的時候能夠不指定具體類型,例如:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace MyGeneric 8 { 9 /// <summary> 10 /// 使用泛型的時候必須指定具體類型, 11 /// 這裏的具體類型是int 12 /// </summary> 13 public class CommonClass :GenericClass<int> 14 { 15 } 16 17 /// <summary> 18 /// 子類也是泛型的,繼承的時候能夠不指定具體類型 19 /// </summary> 20 /// <typeparam name="T"></typeparam> 21 public class CommonClassChild<T>:GenericClass<T> 22 { 23 24 } 25 }
二、類實現泛型接口也是這種狀況,例如:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace MyGeneric 8 { 9 /// <summary> 10 /// 必須指定具體類型 11 /// </summary> 12 public class Common : IGenericInterface<string> 13 { 14 public string GetT(string t) 15 { 16 throw new NotImplementedException(); 17 } 18 } 19 20 /// <summary> 21 /// 能夠不知道具體類型,可是子類也必須是泛型的 22 /// </summary> 23 /// <typeparam name="T"></typeparam> 24 public class CommonChild<T> : IGenericInterface<T> 25 { 26 public T GetT(T t) 27 { 28 throw new NotImplementedException(); 29 } 30 } 31 }
5、泛型約束
先來看看下面的一個例子:
定義一個People類,裏面有屬性和方法:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace MyGeneric 8 { 9 public interface ISports 10 { 11 void Pingpang(); 12 } 13 14 public interface IWork 15 { 16 void Work(); 17 } 18 19 20 public class People 21 { 22 public int Id { get; set; } 23 public string Name { get; set; } 24 25 public void Hi() 26 { 27 Console.WriteLine("Hi"); 28 } 29 } 30 31 public class Chinese : People, ISports, IWork 32 { 33 public void Tradition() 34 { 35 Console.WriteLine("仁義禮智信,溫良恭儉讓"); 36 } 37 public void SayHi() 38 { 39 Console.WriteLine("吃了麼?"); 40 } 41 42 public void Pingpang() 43 { 44 Console.WriteLine("打乒乓球..."); 45 } 46 47 public void Work() 48 { 49 throw new NotImplementedException(); 50 } 51 } 52 53 public class Hubei : Chinese 54 { 55 public Hubei(int version) 56 { } 57 58 public string Changjiang { get; set; } 59 public void Majiang() 60 { 61 Console.WriteLine("打麻將啦。。"); 62 } 63 } 64 65 66 public class Japanese : ISports 67 { 68 public int Id { get; set; } 69 public string Name { get; set; } 70 public void Hi() 71 { 72 Console.WriteLine("Hi"); 73 } 74 public void Pingpang() 75 { 76 Console.WriteLine("打乒乓球..."); 77 } 78 } 79 }
在Main()方法裏面實例化:
1 People people = new People() 2 { 3 Id = 123, 4 Name = "走本身的路" 5 }; 6 Chinese chinese = new Chinese() 7 { 8 Id = 234, 9 Name = "晴天" 10 }; 11 Hubei hubei = new Hubei(123) 12 { 13 Id = 345, 14 Name = "流年" 15 }; 16 Japanese japanese = new Japanese() 17 { 18 Id = 7654, 19 Name = "werwer" 20 };
這時有一個需求:須要打印出Id和Name屬性的值,將ShowObject()方法修改以下:
可是這樣修改報錯了:object類裏面沒有Id和Name屬性,可能會有人說,強制類型轉換一下就好了啊:
1 public static void ShowObject(object oParameter) 2 { 3 Console.WriteLine("This is {0},parameter={1},type={2}", 4 typeof(CommonMethod), oParameter.GetType().Name, oParameter); 5 6 Console.WriteLine($"{((People)oParameter).Id}_{((People)oParameter).Name}"); 7 }
這樣修改之後,代碼不會報錯了,這時咱們在Main()方法裏面調用:
1 CommonMethod.ShowObject(people); 2 CommonMethod.ShowObject(chinese); 3 CommonMethod.ShowObject(hubei); 4 CommonMethod.ShowObject(japanese);
結果:
能夠看出程序報錯了,由於Japanese沒有繼承自People,這裏類型轉換的時候失敗了。這樣會形成類型不安全的問題。那麼怎麼解決類型不安全的問題呢?那就是使用泛型約束。
所謂的泛型約束,實際上就是約束的類型T。使T必須遵循必定的規則。好比T必須繼承自某個類,或者T必須實現某個接口等等。那麼怎麼給泛型指定約束?其實也很簡單,只須要where關鍵字,加上約束的條件。
泛型約束總共有五種。
約束 | s說明 |
T:結構 | 類型參數必須是值類型 |
T:類 | 類型參數必須是引用類型;這一點也適用於任何類、接口、委託或數組類型。 |
T:new() | 類型參數必須具備無參數的公共構造函數。 當與其餘約束一塊兒使用時,new() 約束必須最後指定。 |
T:<基類名> | 類型參數必須是指定的基類或派生自指定的基類。 |
T:<接口名稱> | 類型參數必須是指定的接口或實現指定的接口。 能夠指定多個接口約束。 約束接口也能夠是泛型的。 |
一、基類約束
上面打印的方法約束T類型必須是People類型。
1 /// <summary> 2 /// 基類約束:約束T必須是People類型或者是People的子類 3 /// </summary> 4 /// <typeparam name="T"></typeparam> 5 /// <param name="tParameter"></param> 6 public static void Show<T>(T tParameter) where T : People 7 { 8 Console.WriteLine($"{tParameter.Id}_{tParameter.Name}"); 9 tParameter.Hi(); 10 }
注意:
基類約束時,基類不能是密封類,即不能是sealed類。sealed類表示該類不能被繼承,在這裏用做約束就無任何意義,由於sealed類沒有子類。
二、接口約束
/// <summary> /// 接口約束 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="t"></param> /// <returns></returns> public static T Get<T>(T t) where T : ISports { t.Pingpang(); return t; }
三、引用類型約束 class
引用類型約束保證T必定是引用類型的。
1 /// <summary> 2 /// 引用類型約束 3 /// </summary> 4 /// <typeparam name="T"></typeparam> 5 /// <param name="t"></param> 6 /// <returns></returns> 7 public static T Get<T>(T t) where T : class 8 { 9 return t; 10 }
四、值類型約束 struct
值類型約束保證T必定是值類型的。
1 /// <summary> 2 /// 值類型類型約束 3 /// </summary> 4 /// <typeparam name="T"></typeparam> 5 /// <param name="t"></param> 6 /// <returns></returns> 7 public static T Get<T>(T t) where T : struct 8 { 9 return t; 10 }
五、無參數構造函數約束 new()
1 /// <summary> 2 /// new()約束 3 /// </summary> 4 /// <typeparam name="T"></typeparam> 5 /// <param name="t"></param> 6 /// <returns></returns> 7 public static T Get<T>(T t) where T : new() 8 { 9 return t; 10 }
泛型約束也能夠同時約束多個,例如:
1 public static void Show<T>(T tParameter) 2 where T : People, ISports, IWork, new() 3 { 4 Console.WriteLine($"{tParameter.Id}_{tParameter.Name}"); 5 tParameter.Hi(); 6 tParameter.Pingpang(); 7 tParameter.Work(); 8 }
注意:有多個泛型約束時,new()約束必定是在最後。
6、泛型的協變和逆變
協變和逆變是在.NET 4.0的時候出現的,只能放在接口或者委託的泛型參數前面,out 協變covariant,用來修飾返回值;in:逆變contravariant,用來修飾傳入參數。
先看下面的一個例子:
定義一個Animal類:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace MyGeneric 8 { 9 public class Animal 10 { 11 public int Id { get; set; } 12 } 13 }
而後在定義一個Cat類繼承自Animal類:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace MyGeneric 8 { 9 public class Cat :Animal 10 { 11 public string Name { get; set; } 12 } 13 }
在Main()方法能夠這樣調用:
1 // 直接聲明Animal類 2 Animal animal = new Animal(); 3 // 直接聲明Cat類 4 Cat cat = new Cat(); 5 // 聲明子類對象指向父類 6 Animal animal2 = new Cat(); 7 // 聲明Animal類的集合 8 List<Animal> listAnimal = new List<Animal>(); 9 // 聲明Cat類的集合 10 List<Cat> listCat = new List<Cat>();
那麼問題來了:下面的一句代碼是否是正確的呢?
1 List<Animal> list = new List<Cat>();
可能有人會認爲是正確的:由於一隻Cat屬於Animal,那麼一羣Cat也應該屬於Animal啊。可是實際上這樣聲明是錯誤的:由於List<Cat>和List<Animal>之間沒有父子關係。
這時就能夠用到協變和逆變了。
1 // 協變 2 IEnumerable<Animal> List1 = new List<Animal>(); 3 IEnumerable<Animal> List2 = new List<Cat>();
F12查看定義:
能夠看到,在泛型接口的T前面有一個out關鍵字修飾,並且T只能是返回值類型,不能做爲參數類型,這就是協變。使用了協變之後,左邊聲明的是基類,右邊能夠聲明基類或者基類的子類。
協變除了能夠用在接口上面,也能夠用在委託上面:
1 Func<Animal> func = new Func<Cat>(() => null);
除了使用.NET框架定義好的覺得,咱們還能夠自定義協變,例如:
1 /// <summary> 2 /// out 協變 只能是返回結果 3 /// </summary> 4 /// <typeparam name="T"></typeparam> 5 public interface ICustomerListOut<out T> 6 { 7 T Get(); 8 } 9 10 public class CustomerListOut<T> : ICustomerListOut<T> 11 { 12 public T Get() 13 { 14 return default(T); 15 } 16 }
使用自定義的協變:
1 // 使用自定義協變 2 ICustomerListOut<Animal> customerList1 = new CustomerListOut<Animal>(); 3 ICustomerListOut<Animal> customerList2 = new CustomerListOut<Cat>();
在來看看逆變。
在泛型接口的T前面有一個In關鍵字修飾,並且T只能方法參數,不能做爲返回值類型,這就是逆變。請看下面的自定義逆變:
1 /// <summary> 2 /// 逆變 只能是方法參數 3 /// </summary> 4 /// <typeparam name="T"></typeparam> 5 public interface ICustomerListIn<in T> 6 { 7 void Show(T t); 8 } 9 10 public class CustomerListIn<T> : ICustomerListIn<T> 11 { 12 public void Show(T t) 13 { 14 } 15 }
使用自定義逆變:
1 // 使用自定義逆變 2 ICustomerListIn<Cat> customerListCat1 = new CustomerListIn<Cat>(); 3 ICustomerListIn<Cat> customerListCat2 = new CustomerListIn<Animal>();
協變和逆變也能夠同時使用,看看下面的例子:
1 /// <summary> 2 /// inT 逆變 3 /// outT 協變 4 /// </summary> 5 /// <typeparam name="inT"></typeparam> 6 /// <typeparam name="outT"></typeparam> 7 public interface IMyList<in inT, out outT> 8 { 9 void Show(inT t); 10 outT Get(); 11 outT Do(inT t); 12 } 13 14 public class MyList<T1, T2> : IMyList<T1, T2> 15 { 16 17 public void Show(T1 t) 18 { 19 Console.WriteLine(t.GetType().Name); 20 } 21 22 public T2 Get() 23 { 24 Console.WriteLine(typeof(T2).Name); 25 return default(T2); 26 } 27 28 public T2 Do(T1 t) 29 { 30 Console.WriteLine(t.GetType().Name); 31 Console.WriteLine(typeof(T2).Name); 32 return default(T2); 33 } 34 }
使用:
1 IMyList<Cat, Animal> myList1 = new MyList<Cat, Animal>(); 2 IMyList<Cat, Animal> myList2 = new MyList<Cat, Cat>();//協變 3 IMyList<Cat, Animal> myList3 = new MyList<Animal, Animal>();//逆變 4 IMyList<Cat, Animal> myList4 = new MyList<Animal, Cat>();//逆變+協變
7、泛型緩存
在前面咱們學習過,類中的靜態類型不管實例化多少次,在內存中只會有一個。靜態構造函數只會執行一次。在泛型類中,T類型不一樣,每一個不一樣的T類型,都會產生一個不一樣的副本,因此會產生不一樣的靜態屬性、不一樣的靜態構造函數,請看下面的例子:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace MyGeneric 8 { 9 public class GenericCache<T> 10 { 11 static GenericCache() 12 { 13 Console.WriteLine("This is GenericCache 靜態構造函數"); 14 _TypeTime = string.Format("{0}_{1}", typeof(T).FullName, DateTime.Now.ToString("yyyyMMddHHmmss.fff")); 15 } 16 17 private static string _TypeTime = ""; 18 19 public static string GetCache() 20 { 21 return _TypeTime; 22 } 23 } 24 }
而後新建一個測試類,用來測試GenericCache類的執行順序:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading; 6 using System.Threading.Tasks; 7 8 namespace MyGeneric 9 { 10 public class GenericCacheTest 11 { 12 public static void Show() 13 { 14 for (int i = 0; i < 5; i++) 15 { 16 Console.WriteLine(GenericCache<int>.GetCache()); 17 Thread.Sleep(10); 18 Console.WriteLine(GenericCache<long>.GetCache()); 19 Thread.Sleep(10); 20 Console.WriteLine(GenericCache<DateTime>.GetCache()); 21 Thread.Sleep(10); 22 Console.WriteLine(GenericCache<string>.GetCache()); 23 Thread.Sleep(10); 24 Console.WriteLine(GenericCache<GenericCacheTest>.GetCache()); 25 Thread.Sleep(10); 26 } 27 } 28 } 29 }
Main()方法裏面調用:
1 GenericCacheTest.Show();
結果:
從上面的截圖中能夠看出,泛型會爲不一樣的類型都建立一個副本,因此靜態構造函數會執行5次。 並且每次靜態屬性的值都是同樣的。利用泛型的這一特性,能夠實現緩存。
注意:只能爲不一樣的類型緩存一次。泛型緩存比字典緩存效率高。泛型緩存不能主動釋放