泛型

2.0 版 C# 语言和公共语言运行时 (CLR) 中增加了泛型。 泛型将类型参数的概念引入 .NET Framework,类型参数使得设计如下类和方法成为可能:这些类和方法将一个或多个类型的指定推迟到客户端代码声明并实例化该类或方法的时候。 例如,通过使用泛型类型参数 T,您可以编写其他客户端代码能够使用的单个类,而不致引入运行时强制转换或装箱操作的成本或风险,如下所示:

 

 

 

 1 // Declare the generic class.
 2 public class GenericList<T>
 3 {
 4     void Add(T input) { }
 5 }
 6 class TestGenericList
 7 {
 8     private class ExampleClass { }
 9     static void Main()
10     {
11         // Declare a list of type int.
12         GenericList<int> list1 = new GenericList<int>();
13 // Declare a list of type string.
14         GenericList<string> list2 = new GenericList<string>();
15 // Declare a list of type ExampleClass.
16         GenericList<ExampleClass> list3 = new GenericList<ExampleClass>();
17     }
18 }

 

泛型概述

 

·         使用泛型类型可以最大限度地重用代码、保护类型的安全以及提高性能。

·         泛型最常见的用途是创建集合类。

·         .NET Framework 类库在 System.Collections.Generic 命名空间中包含几个新的泛型集合类。 应尽可能地使用这些类来代替普通的类,如 System.Collections 命名空间中的 ArrayList

·         您可以创建自己的泛型接口、泛型类、泛型方法、泛型事件和泛型委托。

·         可以对泛型类进行约束以访问特定数据类型的方法。

·         关于泛型数据类型中使用的类型的信息可在运行时通过使用反射获取。

 

 

 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 private Node next;
14         public Node Next
15         {
16             get { return next; }
17             set { next = value; }
18         }
19 // T as private member data type.
20         private T data;
21 // T as return type of property.
22         public T Data  
23         {
24             get { return data; }
25             set { data = value; }
26         }
27     }
28 private Node head;
29 // constructor
30     public GenericList() 
31     {
32         head = null;
33     }
34 // T as method parameter type:
35     public void AddHead(T t) 
36     {
37         Node n = new Node(t);
38         n.Next = head;
39         head = n;
40     }
41 public IEnumerator<T> GetEnumerator()
42     {
43         Node current = head;
44 while (current != null)
45         {
46             yield return current.Data;
47             current = current.Next;
48         }
49     }
50 }
51  
52  
53  
54 class TestGenericList
55 {
56     static void Main()
57     {
58         // int is the type argument
59         GenericList<int> list = new GenericList<int>();
60 for (int x = 0; x < 10; x++)
61         {
62             list.AddHead(x);
63         }
64 foreach (int i in list)
65         {
66             System.Console.Write(i + " ");
67         }
68 System.Console.WriteLine("\nDone")
69  }
70  
71  

 

posted @ 2018-01-20 21:57  奔跑的蒲公英  阅读(141)  评论(0编辑  收藏  举报