学习C#基础进阶之c#泛型知识详解
泛型介绍:泛型类和泛型方法同事具备可重用性、类型安全和效率,这是非泛型类和非泛型方法无法具备的。所谓泛型,即通过参数化类型实现同一份代码上操作多种数据类型,泛型编程是一种编程范式,它利用“参数化类型”将类抽象化,从而达到更灵活的复用。
机制:C# 泛型类型替换是在运行时执行的,从而为实例化的对象保留了泛型类型信息。C#泛型代码在被编译为IL代码和无数据时,采用特殊的占位符来表示泛型类型,并用专有的IL指令支持泛型操作。而真正的泛型实例化工作以"on-demand"的方式,发生在JIT编译时。
举例:泛型通常用与集合以及作用于集合的方法一起使用。.NET Framework 2.0 版类库提供一个新的命名空间 System.Collections.Generic,其中包含几个新的基于泛型的集合类。建议面向 2.0 版的所有应用程序都使用新的泛型集合类,而不要使用旧的非泛型集合类,如 ArrayList。
当然,也可以创建自定义泛型类型和方法,以提供自己的通用解决方案,设计类型安全的高效模式。下面的代码示例演示一个用于演示用途的简单泛型链接列表类在通常使用具体类型来指示列表中存储的项的类型的场合,可使用类型参数 T。其使用方法如下:
1、在 AddHead 方法中作为方法参数的类型。
2、在 Node 嵌套类中作为公共方法 GetNext 和 Data 属性的返回类型。
3、在嵌套类中作为私有成员数据的类型。
注意,T 可用于 Node 嵌套类。如果使用具体类型实例化 GenericList<T>(例如,作为 GenericList<int>),则所有的 T 都将被替换为 int。
Code
1// 参数类型T
2public 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 public GenericList()
34 {
35 head = null;
36 }
37
38 // 用T做为方法的参数类型
39 public void AddHead(T t)
40 {
41 Node n = new Node(t);
42 n.Next = head;
43 head = n;
44 }
45
46 public IEnumerator<T> GetEnumerator()
47 {
48 Node current = head;
49
50 while (current != null)
51 {
52 yield return current.Data;
53 current = current.Next;
54 }
55 }
56}