泛型的理解(一)
泛型,英文里表示为通用的(generic),只有在程序运行时才确定他的类型。实现代码的复用。
例如:
private static void Main() { int j = 34; int k = 51; Console.WriteLine("c={0};d={1}", j, k); SwapObj<int>.Swap(ref j, ref k); Console.WriteLine("c={0};d={1}", j, k); } public static class SwapObj<T> { public static void Swap(ref T a, ref T b) { T tmp = a; a = b; b = tmp; }
SwapObj就是简单的泛型类,实现两个相同类型的对象交换。不必为每种类型都写一个类了,大量减少代码。
在运行的时候用SwapObj<int>.指定了是int类型的交换。相当于用int替换了<>中的T。
参考:
http://www.cnblogs.com/xun126/archive/2011/01/13/1933838.html
http://birdshover.cnblogs.com/articles/392127.html