泛型類和泛型方法同時具備可重用性、類型安全和效率,這是非泛型類和非泛型方法無法具備的。泛型通常用在集合和在集合上運行的方法中。.NET Framework 2.0 版類庫提供一個新的命名空間 System.Collections.Generic,其中包含幾個新的基于泛型的集合類。
下面的代碼示例演示一個用于演示用途的簡單泛型鏈接列表類。(大多數情況下,建議使用 .NET Framework 類庫提供的 List<T> 類,而不要自行創建類。)在通常使用具體類型來指示列表中所存儲項的類型時,可使用類型參數 T。其使用方法如下:
(1)在 AddHead 方法中作為方法參數的類型。
(2)在 Node 嵌套類中作為公共方法 GetNext 和 Data 屬性的返回類型。
(3)在嵌套類中作為私有成員數據的類型。
注意,T 可用于 Node 嵌套類。如果使用具體類型實例化 GenericList
public class GenericList<T>
{
// The nested class is also generic on T
private class Node
{
// T used in non-generic constructor
public Node(T t)
{
next = null;
data = t;
}
private Node next;
public Node Next
{
get { return next; }
set { next = value; }
}
// T as private member data type
private T data; // T as return type of property
public T Data
{
get { return data; }
set { data = value; }
}
}
private Node head; // constructor
public GenericList() { head = null; } // T as method parameter type:
public void AddHead(T t)
{
Node n = new Node(t);
n.Next = head;
head = n;
}
public IEnumerator<T> GetEnumerator()
{
Node current = head;
while (current != null)
{
yield return current.Data;
current = current.Next;
}
}
}
下面的代碼示例演示客戶端代碼如何使用泛型 GenericList
{
static void Main()
{
// int is the type argument
GenericList<int> list = new GenericList<int>();
for (int x = 0; x < 10; x++)
{
list.AddHead(x);
}
foreach (int i in list)
{
System.Console.Write(i + " ");
}
System.Console.WriteLine("/nDone");
}
}
新聞熱點
疑難解答