C# 泛型類型參數(shù)淺析
C# 泛型類型參數(shù)在泛型類型或方法定義中,類型參數(shù)是客戶端在實例化泛型類型的變量時指定的特定類型的占位符。泛型類(如 泛型介紹(C# 編程指南)中列出的 GenericList<T>)不可以像這樣使用,因為它實際上并不是一個類型,而更像是一個類型的藍(lán)圖。若要使用 GenericList<T>,客戶端代碼必須通過指定尖括號中的類型參數(shù)來聲明和實例化構(gòu)造類型。此特定類的類型參數(shù)可以是編譯器識別的任何類型。可以創(chuàng)建任意數(shù)目的構(gòu)造類型實例,每個實例使用不同的類型參數(shù),如下所示:
C# 泛型類型參數(shù)代碼
- GenericList<float> list1 = new GenericList<float>();
- GenericList<ExampleClass> list2 = new GenericList<ExampleClass>();
- GenericList<ExampleStruct> list3 = new GenericList<ExampleStruct>();
在每個 GenericList<T> 實例中,類中出現(xiàn)的每個 T 都會在運行時替換為相應(yīng)的類型參數(shù)。通過這種替換方式,我們使用一個類定義創(chuàng)建了三個獨立的類型安全的有效對象。有關(guān) CLR 如何執(zhí)行此替換的更多信息,請參見 運行庫中的泛型(C# 編程指南)。
C# 類型參數(shù)命名準(zhǔn)則
務(wù)必使用描述性名稱命名泛型類型參數(shù),除非單個字母名稱完全可以讓人了解它表示的含義,而描述性名稱不會有更多的意義。
C# 泛型類型參數(shù)代碼
- public interface ISessionChannel<TSession> { /*...*/ }
- public delegate TOutput Converter<TInput, TOutput>(TInput from);
- public class List<T> { /*...*/ }
考慮使用 T 作為具有單個字母類型參數(shù)的類型的類型參數(shù)名。
C# 泛型類型參數(shù)代碼
- public int IComparer<T>() { return 0; }
- public delegate bool Predicate<T>(T item);
- public struct Nullable<T> where T : struct { /*...*/ }
務(wù)必將“T”作為描述性類型參數(shù)名的前綴。
C# 泛型類型參數(shù)代碼
- public interface ISessionChannel<TSession>
- {
- TSession Session { get; }
- }
考慮在參數(shù)名中指示對此類型參數(shù)的約束。例如,可以將帶有 ISession 約束的參數(shù)命名為 TSession。
C# 泛型類型參數(shù)的相關(guān)內(nèi)容就向你介紹到這里,希望對你了解和學(xué)習(xí)C# 泛型類型參數(shù)有所幫助。
【編輯推薦】

















