深入解析C#中的泛型類與泛型接口
泛型類
泛型類封裝不是特定于具體數(shù)據(jù)類型的操作。泛型類最常用于集合,如鏈接列表、哈希表、堆棧、隊(duì)列、樹(shù)等。像從集合中添加和移除項(xiàng)這樣的操作都以大體上相同的方式執(zhí)行,與所存儲(chǔ)數(shù)據(jù)的類型無(wú)關(guān)。
對(duì)于大多數(shù)需要集合類的方案,推薦的方法是使用 .NET Framework 類庫(kù)中所提供的類。
- 一般情況下,創(chuàng)建泛型類的過(guò)程為:從一個(gè)現(xiàn)有的具體類開(kāi)始,逐一將每個(gè)類型更改為類型參數(shù),直至達(dá)到通用化和可用性的最佳平衡。創(chuàng)建您自己的泛型類時(shí),需要特別注意以下事項(xiàng):
- 將哪些類型通用化為類型參數(shù)。
- 通常,能夠參數(shù)化的類型越多,代碼就會(huì)變得越靈活,重用性就越好。但是,太多的通用化會(huì)使其他開(kāi)發(fā)人員難以閱讀或理解代碼。
- 如果存在約束,應(yīng)對(duì)類型參數(shù)應(yīng)用什么約束。
- 一條有用的規(guī)則是,應(yīng)用盡可能最多的約束,但仍使您能夠處理必須處理的類型。例如,如果您知道您的泛型類僅用于引用類型,則應(yīng)用類約束。這可以防止您的類被意外地用于值類型,并允許您對(duì) T 使用 as 運(yùn)算符以及檢查空值。
- 是否將泛型行為分解為基類和子類。
- 由于泛型類可以作為基類使用,此處適用的設(shè)計(jì)注意事項(xiàng)與非泛型類相同。請(qǐng)參見(jiàn)本主題后面有關(guān)從泛型基類繼承的規(guī)則。
- 是否實(shí)現(xiàn)一個(gè)或多個(gè)泛型接口。
例如,如果您設(shè)計(jì)一個(gè)類,該類將用于創(chuàng)建基于泛型的集合中的項(xiàng),則可能必須實(shí)現(xiàn)一個(gè)接口,如 IComparable<T>,其中 T 是您的類的類型。
類型參數(shù)和約束的規(guī)則對(duì)于泛型類行為有幾方面的含義,特別是關(guān)于繼承和成員可訪問(wèn)性。您應(yīng)當(dāng)先理解一些術(shù)語(yǔ),然后再繼續(xù)進(jìn)行。對(duì)于泛型類 Node<T>,客戶端代碼可通過(guò)指定類型參數(shù)來(lái)引用該類,以便創(chuàng)建封閉式構(gòu)造類型 (Node<int>)。或者可以讓類型參數(shù)處于未指定狀態(tài)(例如在指定泛型基類時(shí))以創(chuàng)建開(kāi)放式構(gòu)造類型 (Node<T>)。泛型類可以從具體的、封閉式構(gòu)造或開(kāi)放式構(gòu)造基類繼承:
class BaseNode { } class BaseNodeGeneric<T> { } // concrete type class NodeConcrete<T> : BaseNode { } //closed constructed type class NodeClosed<T> : BaseNodeGeneric<int> { } //open constructed type class NodeOpen<T> : BaseNodeGeneric<T> { }
非泛型類(換句話說(shuō),即具體類)可以從封閉式構(gòu)造基類繼承,但無(wú)法從開(kāi)放式構(gòu)造類或類型參數(shù)繼承,因?yàn)樵谶\(yùn)行時(shí)客戶端代碼無(wú)法提供實(shí)例化基類所需的類型參數(shù)。
//No error class Node1 : BaseNodeGeneric<int> { } //Generates an error //class Node2 : BaseNodeGeneric<T> {} //Generates an error //class Node3 : T {}
從開(kāi)放式構(gòu)造類型繼承的泛型類必須為任何未被繼承類共享的基類類型參數(shù)提供類型變量,如以下代碼所示:
class BaseNodeMultiple<T, U> { } //No error class Node4<T> : BaseNodeMultiple<T, int> { } //No error class Node5<T, U> : BaseNodeMultiple<T, U> { } //Generates an error //class Node6<T> : BaseNodeMultiple<T, U> {}
從開(kāi)放式構(gòu)造類型繼承的泛型類必須指定約束,這些約束是基類型約束的超集或暗示基類型約束:
class NodeItem<T> where T : System.IComparable<T>, new() { } class SpecialNodeItem<T> : NodeItem<T> where T : System.IComparable<T>, new() { }
泛型類型可以使用多個(gè)類型參數(shù)和約束,如下所示:
class SuperKeyType<K, V, U> where U : System.IComparable<U> where V : new() { }
開(kāi)放式構(gòu)造類型和封閉式構(gòu)造類型可以用作方法參數(shù):
void Swap<T>(List<T> list1, List<T> list2) { //code to swap items } void Swap(List<int> list1, List<int> list2) { //code to swap items }
如果某個(gè)泛型類實(shí)現(xiàn)了接口,則可以將該類的所有實(shí)例強(qiáng)制轉(zhuǎn)換為該接口。
泛型類是不變的。也就是說(shuō),如果輸入?yún)?shù)指定 List<BaseClass>,則當(dāng)您嘗試提供 List<DerivedClass> 時(shí),將會(huì)發(fā)生編譯時(shí)錯(cuò)誤。
泛型接口
為泛型集合類或表示集合中項(xiàng)的泛型類定義接口通常很有用。對(duì)于泛型類,使用泛型接口十分可取,例如使用 IComparable<T> 而不使用 IComparable,這樣可以避免值類型的裝箱和取消裝箱操作。.NET Framework 類庫(kù)定義了若干泛型接口,以用于 System.Collections.Generic 命名空間中的集合類。
將接口指定為類型參數(shù)的約束時(shí),只能使用實(shí)現(xiàn)此接口的類型。下面的代碼示例顯示從 SortedList<T> 類派生的 GenericList<T> 類。
SortedList<T> 添加約束 where T : IComparable<T>。這將使 SortedList<T> 中的 BubbleSort 方法能夠?qū)α斜碓厥褂梅盒?CompareTo 方法。在此示例中,列表元素為簡(jiǎn)單類,即實(shí)現(xiàn) Person 的 IComparable<Person>。
//Type parameter T in angle brackets. public class GenericList<T> : System.Collections.Generic.IEnumerable<T> { protected Node head; protected Node current = null; // Nested class is also generic on T protected class Node { public Node next; private T data; //T as private member datatype public Node(T t) //T used in non-generic constructor { next = null; data = t; } public Node Next { get { return next; } set { next = value; } } public T Data //T as return type of property { get { return data; } set { data = value; } } } public GenericList() //constructor { head = null; } public void AddHead(T t) //T as method parameter type { Node n = new Node(t); n.Next = head; head = n; } // Implementation of the iterator public System.Collections.Generic.IEnumerator<T> GetEnumerator() { Node current = head; while (current != null) { yield return current.Data; current = current.Next; } } // IEnumerable<T> inherits from IEnumerable, therefore this class // must implement both the generic and non-generic versions of // GetEnumerator. In most cases, the non-generic method can // simply call the generic method. System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } } public class SortedList<T> : GenericList<T> where T : System.IComparable<T> { // A simple, unoptimized sort algorithm that // orders list elements from lowest to highest: public void BubbleSort() { if (null == head || null == head.Next) { return; } bool swapped; do { Node previous = null; Node current = head; swapped = false; while (current.next != null) { // Because we need to call this method, the SortedList // class is constrained on IEnumerable<T> if (current.Data.CompareTo(current.next.Data) > 0) { Node tmp = current.next; current.next = current.next.next; tmp.next = current; if (previous == null) { head = tmp; } else { previous.next = tmp; } previous = tmp; swapped = true; } else { previous = current; current = current.next; } } } while (swapped); } } // A simple class that implements IComparable<T> using itself as the // type argument. This is a common design pattern in objects that // are stored in generic lists. public class Person : System.IComparable<Person> { string name; int age; public Person(string s, int i) { name = s; age = i; } // This will cause list elements to be sorted on age values. public int CompareTo(Person p) { return age - p.age; } public override string ToString() { return name + ":" + age; } // Must implement Equals. public bool Equals(Person p) { return (this.age == p.age); } } class Program { static void Main() { //Declare and instantiate a new generic SortedList class. //Person is the type argument. SortedList<Person> list = new SortedList<Person>(); //Create name and age values to initialize Person objects. string[] names = new string[] { "Franscoise", "Bill", "Li", "Sandra", "Gunnar", "Alok", "Hiroyuki", "Maria", "Alessandro", "Raul" }; int[] ages = new int[] { 45, 19, 28, 23, 18, 9, 108, 72, 30, 35 }; //Populate the list. for (int x = 0; x < 10; x++) { list.AddHead(new Person(names[x], ages[x])); } //Print out unsorted list. foreach (Person p in list) { System.Console.WriteLine(p.ToString()); } System.Console.WriteLine("Done with unsorted list"); //Sort the list. list.BubbleSort(); //Print out sorted list. foreach (Person p in list) { System.Console.WriteLine(p.ToString()); } System.Console.WriteLine("Done with sorted list"); } }
可將多重接口指定為單個(gè)類型上的約束,如下所示:
class Stack<T> where T : System.IComparable<T>, IEnumerable<T> { }
一個(gè)接口可定義多個(gè)類型參數(shù),如下所示:
interface IDictionary<K, V> { }
適用于類的繼承規(guī)則同樣適用于接口:
interface IMonth<T> { } interface IJanuary : IMonth<int> { } //No error interface IFebruary<T> : IMonth<int> { } //No error interface IMarch<T> : IMonth<T> { } //No error //interface IApril<T> : IMonth<T, U> {} //Error
如果泛型接口為逆變的,即僅使用其類型參數(shù)作為返回值,則此泛型接口可以從非泛型接口繼承。在 .NET Framework 類庫(kù)中,IEnumerable<T> 從 IEnumerable 繼承,因?yàn)?IEnumerable<T> 只在 GetEnumerator 的返回值和 Current 屬性 getter 中使用 T。
具體類可以實(shí)現(xiàn)已關(guān)閉的構(gòu)造接口,如下所示:
interface IBaseInterface<T> { } class SampleClass : IBaseInterface<string> { }
只要類參數(shù)列表提供了接口必需的所有參數(shù),泛型類便可以實(shí)現(xiàn)泛型接口或已關(guān)閉的構(gòu)造接口,如下所示:
interface IBaseInterface1<T> { } interface IBaseInterface2<T, U> { } class SampleClass1<T> : IBaseInterface1<T> { } //No error class SampleClass2<T> : IBaseInterface2<T, string> { } //No error
相關(guān)文章
C#正則表達(dá)式分解和轉(zhuǎn)換IP地址實(shí)例(C#正則表達(dá)式大全 c#正則表達(dá)式語(yǔ)法)
這是我發(fā)了不少時(shí)間整理的C#的正則表達(dá)式,新手朋友注意一定要手冊(cè)一下哦,這樣可以節(jié)省很多寫(xiě)代碼的時(shí)間。下面進(jìn)行了簡(jiǎn)單總結(jié)2013-12-12使用代理模式來(lái)進(jìn)行C#設(shè)計(jì)模式開(kāi)發(fā)的基礎(chǔ)教程
這篇文章主要介紹了使用代理模式來(lái)進(jìn)行C#設(shè)計(jì)模式開(kāi)發(fā)的基礎(chǔ)教程,代理模式主張?jiān)诳蛻舳撕湍繕?biāo)對(duì)象中間建立中介來(lái)降低程序設(shè)計(jì)的耦合度,需要的朋友可以參考下2016-02-02c#委托把方法當(dāng)成參數(shù)(實(shí)例講解)
本篇文章主要是對(duì)c#委托把方法當(dāng)成參數(shù)的實(shí)例代碼進(jìn)行了介紹,需要的朋友可以過(guò)來(lái)參考下,希望對(duì)大家有所幫助2014-01-01SQL+C#實(shí)現(xiàn)獲得當(dāng)前月的第一天與最后一天
本文分享了SQL+C#獲得當(dāng)前月的第一天與最后一天的代碼實(shí)例,代碼簡(jiǎn)潔,適合初學(xué)者參考。需要的朋友可以看下2016-12-12Unity3D實(shí)現(xiàn)攝像機(jī)鏡頭移動(dòng)并限制角度
這篇文章主要為大家詳細(xì)介紹了Unity3D實(shí)現(xiàn)攝像機(jī)鏡頭移動(dòng)并限制角度,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-05-05