在公共语言运行库和 C# 语言的早期版本中,通用化是通过在类型与通用基类型 Object 之间进行强制转换来实现的,泛型提供了针对这种限制的解决方案,可以将一个或多个类型的指定推迟到客户端代码声明并实例化该类或方法的时候。通过创建泛型类,您可以创建一个在编译时类型安全的集合。
泛型的优点
使用非泛型集合类的限制可以通过编写一小段程序来演示,该程序利用 .NET Framework 基类库中的 ArrayList 集合类。ArrayList 是一个使用起来非常方便的集合类,无需进行修改即可用来存储任何引用或值类型。
// The .NET Framework 1.1 way to create a list:
System.Collections.ArrayList list1 = new System.Collections.ArrayList();
list1.Add(3);
list1.Add(105);
System.Collections.ArrayList list2 = new System.Collections.ArrayList();
list2.Add("It is raining in Redmond .");
list2.Add("It is snowing in the mountains.");
但这种方便是需要付出代价的。添加到 ArrayList 中的任何引用或值类型都将隐式地向上强制转换为 Object。如果项是值类型,则必须在将其添加到列表中时进行装箱操作,在检索时进行取消装箱操作。强制转换以及装箱和取消装箱操作都会降低性能;在必须对大型集合进行循环访问的情况下,装箱和取消装箱的影响非常明显。
另一个限制是缺少编译时类型检查;因为 ArrayList 将把所有项都强制转换为 Object,所以在编译时无法防止客户端代码执行以下操作:
System.Collections.ArrayList list = new System.Collections.ArrayList();
// Add an integer to the list.
list.Add(3);
// Add a string to the list. This will compile, but may cause an error later.
list.Add("It is raining in Redmond .");
int t = 0;
// This causes an InvalidCastException to be returned.
foreach (int x in list)
{
t += x;
}
尽管将字符串和 int 组合在一个 ArrayList 中的做法在创建异类集合时是完全合法的,有时是有意图的,但这种做法更可能产生编程错误,并且直到运行时才能检测到此错误。
在 C# 语言的 1.0 和 1.1 版本中,只能通过编写自己的特定于类型的集合来避免 .NET Framework 基类库集合类中的通用代码的危险。当然,由于此类不可对多个数据类型重用,因此将丧失通用化的优点,并且您必须对要存储的每个类型重新编写该类。
ArrayList 和其他相似类真正需要的是:客户端代码基于每个实例指定这些类要使用的具体数据类型的方式。这样将不再需要向上强制转换为 T:System.Object,同时,也使得编译器可以进行类型检查。换句话说,ArrayList 需要一个 type parameter。这正是泛型所能提供的。在 N:System.Collections.Generic 命名空间的泛型 List<T> 集合中,向该集合添加项的操作类似于以下形式:
// The .NET Framework 2.0 way to create a list
List<int> list1 = new List<int>();
// No boxing, no casting:
list1.Add(3);
// Compile-time error:
// list1.Add("It is raining in Redmond .");
对于客户端代码,与 ArrayList 相比,使用 List<T> 时添加的唯一语法是声明和实例化中的类型参数。虽然这稍微增加了些编码的复杂性,但好处是您可以创建一个比 ArrayList 更安全并且速度更快的列表,特别适用于列表项是值类型的情况。
归纳起来,泛型比非泛型具有下面两个优点:
1、 更加安全
在非泛型编程中,虽然所有的东西都可以作为Object传递,但是在传递的过程中免不了要进行类型转换。而类型转换在运行时是不安全的。使用泛型编程将可以减少不必要的类型转换,从而提高安全性。不仅是值类型,引用类型也存在这样的问题,因此有必要的尽量的去使用泛型集合。
2、 效率更高
在非泛型编程中,将简单类型作为Object传递时会引起装箱和拆箱的操作,这两个过程都是具有很大开销的。使用泛型编程就不必进行装箱和拆箱操作了。
泛型集合
通常情况下,建议您使用泛型集合,因为这样可以获得类型安全的直接优点而不需要从基集合类型派生并实现类型特定的成员。下面的泛型类型对应于现有的集合类型:
· Dictionary 是对应于 Hashtable 的泛型类。
· Collection 是对应于 CollectionBase 的泛型类。Collection 可以用作基类,但是与 CollectionBase 不同的是它不是抽象的,因而更易于使用。
· ReadOnlyCollection 是对应于 ReadOnlyCollectionBase 的泛型类。ReadOnlyCollection 不是抽象的,它具有一个构造函数,该构造函数使其更易于将现有的 List 公开为只读集合。
· Queue、Stack 和 SortedList 泛型类分别对应于与其同名的非泛型类。
有几种泛型集合类型没有对应的非泛型类型:
· LinkedList 是一个通用链接列表,它提供运算复杂度为 O(1) 的插入和移除操作。
· SortedDictionary 是一个排序的字典,其插入和检索操作的运算复杂度为 O(log n),这使得它成为 SortedList 的十分有用的替代类型。
· KeyedCollection 是介于列表和字典之间的混合类型,它提供了一种存储包含自己键的对象的方法。
类型参数的约束
class EmployeeList<T> where T : Employee, IEmployee, System.IComparable<T>, new()
{
// ...
}
其中
T:new() | 类型参数必须具有无参数的公共构造函数。当与其他约束一起使用时,new() 约束必须最后指定。 |
T:类 | 类型参数必须是引用类型,包括任何类、接口、委托或数组类型。 |
遍历集合类
遍历一个实现了IEnumerable<T>接口的GetEnumerator()方法的集合,可以使用foreach来进行遍历
public class GenericList<T> : System.Collections.Generic.IEnumerable<T>{
// Implementation of the iterator
public System.Collections.Generic.IEnumerator<T> GetEnumerator()
{
Node current = head;
while (current != null)
{
yield return current.Data;
current = current.Next;
}
}
}
//Print out sorted list.
foreach (Person p in list)
{
System.Console.WriteLine(p.ToString());
}
泛型接口(C# 编程指南),排序,System.Collections.Generic.IEnumerable<T> System.IComparable<T>
为泛型集合类或表示集合中项的泛型类定义接口通常很有用。对于泛型类,使用泛型接口十分可取,例如使用 IComparable<T> 而不使用 IComparable,这样可以避免值类型的装箱和取消装箱操作。.NET Framework 2.0 类库定义了若干新的泛型接口,以用于 System.Collections.Generic 命名空间中新的集合类。
将接口指定为类型参数的约束时,只能使用实现此接口的类型。下面的代码示例显示从 GenericList<T> 类派生的 SortedList<T> 类。有关更多信息,请参见泛型介绍(C# 编程指南)。SortedList<T> 添加了约束 where T : IComparable<T>。这将使 SortedList<T> 中的 BubbleSort 方法能够对列表元素使用泛型 CompareTo 方法。在此示例中,列表元素为简单类,即实现 IComparable<Person> 的 Person。
C# | 复制代码 |
//Type parameter T in angle brackets. public class GenericList<T> : System.Collections.Generic.IEnumerable<T> { protected Node head; protected Node current = null;
// Nested class is also generic on T protected class Node { public Node next; private T data; //T as private member datatype
public Node(T t) //T used in non-generic constructor { next = null; data = t; }
public Node Next { get { return next; } set { next = value; } }
public T Data //T as return type of property { get { return data; } set { data = value; } } }
public GenericList() //constructor { head = null; }
public void AddHead(T t) //T as method parameter type { Node n = new Node(t); n.Next = head; head = n; }
// Implementation of the iterator public System.Collections.Generic.IEnumerator<T> GetEnumerator() { Node current = head; while (current != null) { yield return current.Data; current = current.Next; } }
// IEnumerable<T> inherits from IEnumerable, therefore this class // must implement both the generic and non-generic versions of // GetEnumerator. In most cases, the non-generic method can // simply call the generic method. System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } }
public class SortedList<T> : GenericList<T> where T : System.IComparable<T> { // A simple, unoptimized sort algorithm that // orders list elements from lowest to highest:
public void BubbleSort() { if (null == head || null == head.Next) { return; } bool swapped;
do { Node previous = null; Node current = head; swapped = false;
while (current.next != null) { // Because we need to call this method, the SortedList // class is constrained on IEnumerable<T> if (current.Data.CompareTo(current.next.Data) > 0) { Node tmp = current.next; current.next = current.next.next; tmp.next = current;
if (previous == null) { head = tmp; } else { previous.next = tmp; } previous = tmp; swapped = true; } else { previous = current; current = current.next; } } } while (swapped); } }
// A simple class that implements IComparable<T> using itself as the // type argument. This is a common design pattern in objects that // are stored in generic lists. public class Person : System.IComparable<Person> { string name; int age;
public Person(string s, int i) { name = s; age = i; }
// This will cause list elements to be sorted on age values. public int CompareTo(Person p) { return age - p.age; }
public override string ToString() { return name + ":" + age; }
// Must implement Equals. public bool Equals(Person p) { return (this.age == p.age); } }
class Program { static void Main () { //Declare and instantiate a new generic SortedList class. //Person is the type argument. SortedList<Person> list = new SortedList<Person>();
//Create name and age values to initialize Person objects. string[] names = new string[] { "Franscoise", "Bill", "Li", "Sandra", "Gunnar", "Alok", "Hiroyuki", "Maria", "Alessandro", "Raul" };
int[] ages = new int[] { 45, 19, 28, 23, 18, 9, 108, 72, 30, 35 };
//Populate the list. for (int x = 0; x < 10; x++) { list.AddHead(new Person(names[x], ages[x])); }
//Print out unsorted list. foreach (Person p in list) { System.Console.WriteLine(p.ToString()); } System.Console.WriteLine("Done with unsorted list");
//Sort the list. list.BubbleSort();
//Print out sorted list. foreach (Person p in list) { System.Console.WriteLine(p.ToString()); } System.Console.WriteLine("Done with sorted list"); } } |
可将多重接口指定为单个类型上的约束,如下所示:
C# | 复制代码 |
class Stack<T> where T : System.IComparable<T>, IEnumerable<T> { } |
一个接口可定义多个类型参数,如下所示:
C# | 复制代码 |
interface IDictionary<K, V> { } |
类之间的继承规则同样适用于接口:
C# | 复制代码 |
interface IMonth<T> { }
interface IJanuary : IMonth<int> { } //No error interface IFebruary<T> : IMonth<int> { } //No error interface IMarch<T> : IMonth<T> { } //No error //interface IApril<T> : IMonth<T, U> {} //Error |
如果泛型接口为逆变的,即仅使用其类型参数作为返回值,则此泛型接口可以从非泛型接口继承。在 .NET Framework 类库中,IEnumerable<T> 从 IEnumerable 继承,因为 IEnumerable<T> 仅在 GetEnumerator 的返回值和当前属性 getter 中使用 T。
具体类可以实现已关闭的构造接口,如下所示:
C# | 复制代码 |
interface IBaseInterface<T> { }
class SampleClass : IBaseInterface<string> { } |
只要类参数列表提供了接口必需的所有参数,泛型类便可以实现泛型接口或已关闭的构造接口,如下所示:
C# | 复制代码 |
interface IBaseInterface1<T> { } interface IBaseInterface2<T, U> { }
class SampleClass1<T> : IBaseInterface1<T> { } //No error class SampleClass2<T> : IBaseInterface2<T, string> { } //No error |
对于泛型类、泛型结构或泛型接口中的方法,控制方法重载的规则相同。