【已更新最新开发文章,点击查看详细】
C# 语言和公共语言运行时 (CLR) 的 2.0 版本中添加了泛型。 泛型将类型参数的概念引入 .NET Framework,这样就可以设计具有以下特征的类和方法:在客户端代码声明并初始化这些类和方法之前,这些类和方法会延迟指定一个或多个类型。
泛型定义
泛型是为所存储或使用的一个或多个类型具有占位符(类型形参)的类、结构、接口和方法。 泛型集合类可以将类型形参用作其存储的对象类型的占位符;类型形参呈现为其字段的类型和其方法的参数类型。 泛型方法可将其类型形参用作其返回值的类型或用作其形参之一的类型。
public class Generic<T> { public T Field; }
你将得到根据你选择的类型而定制的类型安全类,如以下代码所示。
public static void Main() { Generic<string> g = new Generic<string>(); g.Field = "A string"; //... Console.WriteLine("Generic.Field = \"{0}\"", g.Field); Console.WriteLine("Generic.Field.GetType() = {0}", g.Field.GetType().FullName); }
例如,通过使用泛型类型参数 T,可以编写其他客户端代码能够使用的单个类,而不会产生运行时转换或装箱操作的成本或风险,如下所示:
// 定义通用泛型类 public class GenericList<T> { public void Add(T input) { } }
class TestGenericList { private class ExampleClass { } static void Main() { // 定义 int 类型的集合 GenericList<int> list1 = new GenericList<int>(); list1.Add(1); // 定义 string 类型的集合 GenericList<string> list2 = new GenericList<string>(); list2.Add(""); // 定义 ExampleClass 类类型的集合 GenericList<ExampleClass> list3 = new GenericList<ExampleClass>(); list3.Add(new ExampleClass()); } }
.NET 中的泛型。
其使用方法如下:
-
在
AddHead方法中作为方法参数的类型。 -
在
Node嵌套类中作为Data属性的返回类型。 -
在嵌套类中作为私有成员
data的类型。
如果使用具体类型实例化 GenericList<T>(例如,作为 GenericList<int>),则出现的所有 T 都将替换为 int。
// 泛型 T 类型的类 public class GenericList<T> { // 嵌套类也定义成泛型T类型 private class Node { // 泛型类型 T 作为构造函数参数 public Node(T t) { next = null; data = t; } private Node next; public Node Next { get { return next; } set { next = value; } } // 定义一个私有 T(类型) 数据类型的变量 private T data; // T 类型作为属性的返回类型 public T Data { get { return data; } set { data = value; } } } private Node head; // 构造函数 public GenericList() { head = null; } // T 作为方法的参数类型 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; } } }
只需更改类型参数,即可轻松修改以下代码,创建字符串或任何其他自定义类型的列表:
class TestGenericList { static void Main() { // 定义 int 类型的集合 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("\n 完成"); } }
泛型主要有两个优点:
- 编译时可以保证类型安全。
- 不用做类型转换,获得一定的性能提升。
泛型概述
-
使用泛型类型可以最大限度地重用代码、保护类型安全性以及提高性能。
-
泛型最常见的用途是创建集合类。
-
ArrayList。
-
可以创建自己的泛型接口、泛型类、泛型方法、泛型事件和泛型委托。
-
可以对泛型类进行约束以访问特定数据类型的方法。
-
在泛型数据类型中所用类型的信息可在运行时通过使用反射来获取。
相关章节
更多相关信息:
【已更新最新开发文章,点击查看详细】