代码重用
泛型(generic)是CLR和编程语言提供的一种特殊机制,它支持一种形式的代码重用,即“算法重用”。
简单地说,开发人员先定义好一个算法,比如排序、搜索、交换、比较或者转换等。但是,定义算法的开发人员并不设定该算法要操作什么数据类型;该算法可广泛地应用于不同类型的对象。然后,另一个开发人员只要指定了算法要操作的具体数据类型,就可以开始使用这个现成的算法了。
CLR允许在引用类型、值类型或接口中定义泛型方法。
封装了泛型列表算法的FCL类称为List<T>(读作List of Tee)。这个类是在System.Collections.Generic命名空间中定义的。
[Serializable]
public class List<T>:IList<T>,ICollection<T>,IEnumerable<T>,IList,ICollection,IEnumerable{
public List();
public void Add(T item);
public Int32 BinarySearch(T item);
public void Clear();
public Boolean Contains(T item);
public Int32 IndexOf(T item);
public Boolean Remove(T item);
public void Sort();
public void Sort(ICompare<T> comparer);
public void SOrt(Comparison<T> comparison);
public T[] ToArray();
public Int32 Count{get;}
public T this[Int32 index]{get;set}
}
泛型List类的设计者紧接在类名后添加了一个<T>,表明它操作的是一个未指定的数据类型。由于凡是能指定一个数据类型的地方都能使用T变量,所以在方法内部定义一个局部变量时,或者在类型中定义字段时,也可以使用T。
优势: 源代码保护,类型安全,更加清晰的代码,更佳的性能
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Collections;
namespace log4net
{
class P
{
public static void Main() {
ValueTypePerfTest();
ReferenceTypePerfTest();
}
private static void ValueTypePerfTest() {
const Int32 count = 10000000;
using (new OperationTimer("List<Int32>")) {
List<Int32> l = new List<int>(count);
for (int n = 0; n < count; n++) {
l.Add(n);
int x = l[n];
}
l = null;//确保进行垃圾回收
}
using (new OperationTimer("ArrayList of Int32")) {
ArrayList a = new ArrayList();
for (int n = 0; n < count; n++) {
a.Add(n);
int x = (int)a[n];
}
a = null;//确保进行垃圾回收
}
}
private static void ReferenceTypePerfTest() {
const int count = 10000000;
using (new OperationTimer("List<String>")) {
List<String> l = new List<string>();
for(int n=0;n<count;n++){
l.Add("X");
String x = l[n];
}
l = null;//确保进行垃圾回收
}
using (new OperationTimer("ArrayList of String")) {
ArrayList a = new ArrayList();
for (int n = 0; n < count; n++) {
a.Add("X");
String x = (String)a[n];
}
a = null;//确保进行垃圾回收
}
}
}
internal sealed class OperationTimer : IDisposable {
private Int64 m_startTime;
private String m_text;
private Int32 m_collectionCount;
public OperationTimer(String text) {
PrepareForOperation();
m_text = text;
m_collectionCount = GC.CollectionCount(0);
//这应该是方法的最后一个语句,从而最大程序保证计时的准确性
m_startTime = Stopwatch.GetTimestamp();
}
public void Dispose() {
Console.WriteLine("{0.6:###.00} seconds (GCs={1,3}) {2}",
(Stopwatch.GetTimestamp() - m_startTime) /
(Double)Stopwatch.Frequency,
GC.CollectionCount(0) - m_collectionCount, m_text);
}
public static void PrepareForOperation() {
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
}
}
泛型最明显的应用就是集合类。