用自定义泛型实现交换任意类型的两个变量。
1 class Program 2 { 3 static void Main(string[] args) 4 { 5 int a = 10, b = 90; 6 Console.WriteLine("Before swap: {0}, {1}", a, b); 7 Swap<int>(ref a, ref b); 8 Console.WriteLine("After swap: {0}, {1}", a, b); 9 Console.WriteLine("---------------------"); 10 11 string s1 = "Hello", s2 = "World"; 12 Console.WriteLine("Before swap: {0} {1}", s1, s2); 13 Swap<string>(ref s1, ref s2); 14 Console.WriteLine("After swap: {0} {1}", s1, s2); 15 Console.WriteLine("---------------------"); 16 17 bool b1 = true, b2 = false; 18 Console.WriteLine("Before swap: {0} , {1}", b1, b2); 19 Swap<bool>(ref b1, ref b2); 20 Console.WriteLine("After swap: {0} , {1}", b1, b2); 21 Console.WriteLine("---------------------"); 22 23 DisplayBaseClass<int>(); 24 DisplayBaseClass<string>(); 25 26 Console.ReadLine(); 27 } 28 29 static void Swap<T>(ref T a, ref T b) 30 { 31 Console.WriteLine("You sent the Swap() method a {0}", typeof(T)); 32 T temp; 33 temp = a; 34 a = b; 35 b = temp; 36 } 37 38 static void DisplayBaseClass<T>() 39 { 40 Console.WriteLine("Base class of {0} is : {1}", typeof(T), typeof(T).BaseType); 41 }
注:引用自 《Por C# 2010 and the .NET 4 Platform》