本帖最后由 许晓华 于 2012-12-25 15:32 编辑
楼上谈了泛型的类型安全与高效率的优点。我再补充一个泛型非常重要的优点:代码重用
先看一段重用性低的代码(没有使用泛型)- using System;
- class Program
- {
- static void Main(string[] args)
- {
- int a = 2;
- int b = 9;
- Console.WriteLine("初始时a={0},b={1}", a, b);
- Swap(ref a, ref b);
- Console.WriteLine("交换后a={0},b={1}", a, b);
- float c = 2.5F;
- float d = 9.9F;
- Console.WriteLine("初始时a={0},b={1}", c, d);
- Swap(ref c, ref d);
- Console.WriteLine("交换后a={0},b={1}", c, d);
- string e = "Hello";
- string f = "World";
- Console.WriteLine("初始时a={0},b={1}", e, f);
- Swap(ref e, ref f);
- Console.WriteLine("交换后a={0},b={1}", e, f);
- }
- public static void Swap(ref int a, ref int b)
- {
- int c;
- c = a;
- a = b;
- b = c;
- }
- public static void Swap(ref float a, ref float b)
- {
- float c;
- c = a;
- a = b;
- b = c;
- }
- public static void Swap(ref string a, ref string b)
- {
- string c;
- c = a;
- a = b;
- b = c;
- }
- }
复制代码 |