泛型類
泛型類封裝不是特定于具體數據類型的操作。泛型類最常用于集合,如鏈接列表、哈希表、堆棧、隊列、樹等。像從集合中添加和移除項這樣的操作都以大體上相同的方式執行,與所存儲數據的類型無關。
對于大多數需要集合類的方案,推薦的方法是使用 .NET Framework 類庫中所提供的類。
例如,如果您設計一個類,該類將用于創建基于泛型的集合中的項,則可能必須實現一個接口,如 IComparable<T>,其中 T 是您的類的類型。
類型參數和約束的規則對于泛型類行為有幾方面的含義,特別是關于繼承和成員可訪問性。您應當先理解一些術語,然后再繼續進行。對于泛型類 Node<T>,客戶端代碼可通過指定類型參數來引用該類,以便創建封閉式構造類型 (Node<int>)?;蛘呖梢宰岊愋蛥堤幱谖粗付顟B(例如在指定泛型基類時)以創建開放式構造類型 (Node<T>)。泛型類可以從具體的、封閉式構造或開放式構造基類繼承:
class BaseNode { }class BaseNodeGeneric<T> { }// concrete typeclass NodeConcrete<T> : BaseNode { }//closed constructed typeclass NodeClosed<T> : BaseNodeGeneric<int> { }//open constructed type class NodeOpen<T> : BaseNodeGeneric<T> { }
非泛型類(換句話說,即具體類)可以從封閉式構造基類繼承,但無法從開放式構造類或類型參數繼承,因為在運行時客戶端代碼無法提供實例化基類所需的類型參數。
//No errorclass Node1 : BaseNodeGeneric<int> { }//Generates an error//class Node2 : BaseNodeGeneric<T> {}//Generates an error//class Node3 : T {}
從開放式構造類型繼承的泛型類必須為任何未被繼承類共享的基類類型參數提供類型變量,如以下代碼所示:
class BaseNodeMultiple<T, U> { }//No errorclass Node4<T> : BaseNodeMultiple<T, int> { }//No errorclass Node5<T, U> : BaseNodeMultiple<T, U> { }//Generates an error//class Node6<T> : BaseNodeMultiple<T, U> {}
從開放式構造類型繼承的泛型類必須指定約束,這些約束是基類型約束的超集或暗示基類型約束:
class NodeItem<T> where T : System.IComparable<T>, new() { }class SpecialNodeItem<T> : NodeItem<T> where T : System.IComparable<T>, new() { }
泛型類型可以使用多個類型參數和約束,如下所示:
class SuperKeyType<K, V, U> where U : System.IComparable<U> where V : new(){ }
開放式構造類型和封閉式構造類型可以用作方法參數:
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}
如果某個泛型類實現了接口,則可以將該類的所有實例強制轉換為該接口。
泛型類是不變的。也就是說,如果輸入參數指定 List<BaseClass>,則當您嘗試提供 List<DerivedClass> 時,將會發生編譯時錯誤。
泛型接口
為泛型集合類或表示集合中項的泛型類定義接口通常很有用。對于泛型類,使用泛型接口十分可取,例如使用 IComparable<T> 而不使用 IComparable,這樣可以避免值類型的裝箱和取消裝箱操作。.NET Framework 類庫定義了若干泛型接口,以用于 System.Collections.Generic 命名空間中的集合類。
將接口指定為類型參數的約束時,只能使用實現此接口的類型。下面的代碼示例顯示從 SortedList<T> 類派生的 GenericList<T> 類。
SortedList<T> 添加約束 where T : IComparable<T>。這將使 SortedList<T> 中的 BubbleSort 方法能夠對列表元素使用泛型 CompareTo 方法。在此示例中,列表元素為簡單類,即實現 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"); }}
可將多重接口指定為單個類型上的約束,如下所示:
class Stack<T> where T : System.IComparable<T>, IEnumerable<T>{}
一個接口可定義多個類型參數,如下所示:
interface IDictionary<K, V>{}
適用于類的繼承規則同樣適用于接口:
interface IMonth<T> { }interface IJanuary : IMonth<int> { } //No errorinterface IFebruary<T> : IMonth<int> { } //No errorinterface IMarch<T> : IMonth<T> { } //No error//interface IApril<T> : IMonth<T, U> {} //Error
如果泛型接口為逆變的,即僅使用其類型參數作為返回值,則此泛型接口可以從非泛型接口繼承。在 .NET Framework 類庫中,IEnumerable<T> 從 IEnumerable 繼承,因為 IEnumerable<T> 只在 GetEnumerator 的返回值和 Current 屬性 getter 中使用 T。
具體類可以實現已關閉的構造接口,如下所示:
interface IBaseInterface<T> { }class SampleClass : IBaseInterface<string> { }
只要類參數列表提供了接口必需的所有參數,泛型類便可以實現泛型接口或已關閉的構造接口,如下所示:
interface IBaseInterface1<T> { }interface IBaseInterface2<T, U> { }class SampleClass1<T> : IBaseInterface1<T> { } //No errorclass SampleClass2<T> : IBaseInterface2<T, string> { } //No error
新聞熱點
疑難解答