|
泛型类和泛型方法同时具备可重用性、类型安全和效率,这是非泛型类和非泛型方法无法具备的。泛型通常用在集合和在集合上运行的方法中。.NET Framework 2.0 版类库提供一个新的命名空间 System.Collections.Generic,其中包含几个新的基于泛型的集合类。建议面向 2.0 版的所有应用程序都使用新的泛型集合类,而不要使用旧的非泛型集合类,如 ArrayList。有关更多信息,请参见 .NET Framework 类库中的泛型(C# 编程指南)。
当然,也可以创建自定义泛型类型和方法,以提供自己的通用解决方案,设计类型安全的高效模式。下面的代码示例演示一个用于演示用途的简单泛型链接列表类。(大多数情况下,建议使用 .NET Framework 类库提供的 List<T> 类,而不要自行创建类。)在通常使用具体类型来指示列表中所存储项的类型时,可使用类型参数 T。其使用方法如下:
在 AddHead 方法中作为方法参数的类型。
在 Node 嵌套类中作为公共方法 GetNext 和 Data 属性的返回类型。
在嵌套类中作为私有成员数据的类型。
注意,T 可用于 Node 嵌套类。如果使用具体类型实例化 GenericList<T>(例如,作为 GenericList<int>),则所有的 T 都将被替换为 int。
1 // type parameter T in angle brackets 2 public class GenericList<T> 3  { 4 // The nested class is also generic on T 5 private class Node 6 { 7 // T used in non-generic constructor 8 public Node(T t) 9 { 10 next = null; 11 data = t; 12 } 13 14 private Node next; 15 public Node Next 16 { 17 get { return next; } 18 set { next = value; } 19 } 20 21 // T as private member data type 22 private T data; 23 24 // T as return type of property 25 public T Data 26 { 27 get { return data; } 28 set { data = value; } 29 } 30 } 31 32 private Node head; 33 34 // constructor 35 public GenericList() 36 { 37 head = null; 38 } 39 40 // T as method parameter type: 41 public void AddHead(T t) 42 { 43 Node n = new Node(t); 44 n.Next = head; 45 head = n; 46 } 47 48 public IEnumerator<T> GetEnumerator() 49 { 50 Node current = head; 51 52 while (current != null) 53 { 54 yield return current.Data; 55 current = current.Next; 56 } 57 } 58 } 59 60
下面的代码示例演示客户端代码如何使用泛型 GenericList<T> 类来创建整数列表。只需更改类型参数,即可方便地修改下面的代码示例,创建字符串或任何其他自定义类型的列表:
1 class TestGenericList 2  { 3 static void Main() 4 { 5 // int is the type argument 6 GenericList<int> list = new GenericList<int>(); 7 8 for (int x = 0; x < 10; x++) 9 { 10 list.AddHead(x); 11 } 12 13 foreach (int i in list) 14 { 15 System.Console.Write(i + " "); 16 } 17 System.Console.WriteLine("\nDone"); 18 } 19 } 20 21
共2页: 上一页 1 [2] 下一页
|