深刻解析C#中的泛型類與泛型接口。本站提示廣大學習愛好者:(深刻解析C#中的泛型類與泛型接口)文章只能為提供參考,不一定能成為您想要的結果。以下是深刻解析C#中的泛型類與泛型接口正文
泛型類
泛型類封裝不是特定於詳細數據類型的操作。泛型類最經常使用於聚集,如鏈接列表、哈希表、客棧、隊列、樹等。像從聚集中添加和移除項如許的操作都以年夜體上雷同的方法履行,與所存儲數據的類型有關。
關於年夜多半須要聚集類的計劃,推舉的辦法是應用 .NET Framework 類庫中所供給的類。
例如,假如您設計一個類,該類將用於創立基於泛型的聚集中的項,則能夠必需完成一個接口,如 IComparable<T>,個中 T 是您的類的類型。
類型參數和束縛的規矩關於泛型類行動有幾方面的寄義,特殊是關於繼續和成員可拜訪性。您應該先懂得一些術語,然後再持續停止。關於泛型類 Node<T>,客戶端代碼可經由過程指定類型參數來援用該類,以便創立關閉式結構類型 (Node<int>)。或許可讓類型參數處於未指定狀況(例如在指定泛型基類時)以創立開放式結構類型 (Node<T>)。泛型類可以從詳細的、關閉式結構或開放式結構基類繼續:
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> { }
非泛型類(換句話說,即詳細類)可以從關閉式結構基類繼續,但沒法從開放式結構類或類型參數繼續,由於在運轉時客戶端代碼沒法供給實例化基類所需的類型參數。
//No error
class Node1 : BaseNodeGeneric<int> { }
//Generates an error
//class Node2 : BaseNodeGeneric<T> {}
//Generates an error
//class Node3 : T {}
從開放式結構類型繼續的泛型類必需為任何未被繼續類同享的基類類型參數供給類型變量,如以下代碼所示:
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> {}
從開放式結構類型繼續的泛型類必需指定束縛,這些束縛是基類型束縛的超集或暗示基類型束縛:
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 error
interface IFebruary<T> : IMonth<int> { } //No error
interface 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 error
class SampleClass2<T> : IBaseInterface2<T, string> { } //No error