C#:泛型類
阿新 • • 發佈:2020-11-22
對於泛型類,我們一定十分熟悉了。比如:List
泛型型別的宣告,在C#:泛型中已經提及,但是並未給出一個實際工作中應用的示例;
我們會遇到一些場景:使用者登入登入等資訊;股票的行情資料等,他們無論在程式的任何位置訪問時都應該是同一份;這時候就需要使用到單例模式了:不允許使用者建立該型別的例項,而是為該型別例項提供一個全域性訪問點,從而保證整個程式中的該型別物件只有一個。
如果專案中需要支援單例模式的型別有多個,那麼就需要為每個型別編寫單例模式的實現程式碼;而這些實現程式碼又是高度相似的。說到這裡你或許就知道怎麼搞定這個麻煩事兒了,提供一個泛型單例型別。
泛型單例:它是一種泛型型別;型別引數(如:T)用來代替需要支援單例模式的型別;提供一個公開的、返回值型別為T、的靜態方法。
class SingleTonBase<T> where T : class { private static T _instance; public static readonly object SyncObject = new object(); public static T GetInstance() { if (_instance == null)//為了防止每次都要獲取鎖,增加程式耗時 { lock (SyncObject)//同步鎖,防止例項被同時訪問 { if (_instance == null) { _instance = (T) Activator.CreateInstance(typeof(T), true); } } } return _instance; } public static void SetInstance(T value) { _instance = value; } }
使用方式:
class Program { static void Main(string[] args) { for (int i = 0; i < 10; i++) { Thread thread=new Thread(new ThreadStart(TestSingleton)); thread.Start(); } Console.ReadLine(); } static void TestSingleton() { Student student = SingleTonBase<Student>.GetInstance(); Console.WriteLine($"{student.GetHashCode()}:{student.StudentName},{student.StudentAge}"); } } class Student { private Student() { StudentName = "admin"; StudentAge = 18; Console.WriteLine("建構函式執行..."); } public string StudentName { get; set; } public int StudentAge { get; set; } }
執行結果:
建構函式執行...
12036987:admin,18
12036987:admin,18
12036987:admin,18
12036987:admin,18
12036987:admin,18
12036987:admin,18
12036987:admin,18
12036987:admin,18
12036987:admin,18
12036987:admin,18
通過執行結果可以看出:通過泛型型別SingleTonBase
以上便是對泛型型別的知識總結,記錄下來以便以後檢視。