1 using System; 2 3 namespace 泛型委托 4 { 5 class Program 6 { 7 private delegate bool DelCompare(object o1, object o2); 8 9 private delegate bool Compare<T>(T t1, T t2); 10 static void Main(string[] args) 11 { 12 string[] strings = { "C#", "FrameWork", ".net" }; 13 int[] ints = { 1, 2, 3, 4, 5 }; 14 15 // 1. 普通方法 16 string maxString = GetMaxString(strings); 17 int maxInt = GetMaxInt(ints); 18 Console.WriteLine(maxString); 19 Console.WriteLine(maxInt); 20 21 // 2. 委托方法 22 // 比较麻烦,需要装拆箱 23 object[] strings2 = { "C#", "FrameWork", ".net" }; 24 object[] ints2 = { 1, 2, 3, 4, 5 }; 25 maxString = (string)GetMax(strings2, CompareString); 26 maxInt = (int)GetMax( 27 ints2, 28 delegate (object o1, object o2) 29 { 30 // 拆箱 31 int i1 = (int)o1; 32 int i2 = (int)o2; 33 return i1 < i2; 34 }); 35 Console.WriteLine(maxString); 36 Console.WriteLine(maxInt); 37 38 // 3. 泛型委托 39 // 语法简单,性能高 40 maxString = GetMaxT<string>(strings, (s1, s2) => { return s1.Length < s2.Length; }); 41 maxInt = GetMaxT<int>(ints, (i1, i2) => i1 < i2); 42 Console.WriteLine(maxString); 43 Console.WriteLine(maxInt); 44 45 Console.ReadKey(); 46 } 47 48 #region 普通方法 49 50 private static string GetMaxString(string[] strings) 51 { 52 string max = strings[0]; 53 foreach (var s in strings) 54 { 55 if (max.Length < s.Length) 56 { 57 max = s; 58 } 59 } 60 61 return max; 62 } 63 64 private static int GetMaxInt(int[] ints) 65 { 66 int max = ints[0]; 67 foreach (var i in ints) 68 { 69 if (max < i) 70 { 71 max = i; 72 } 73 } 74 75 return max; 76 } 77 78 #endregion 79 80 #region 委托方法 81 82 private static object GetMax(object[] objects, DelCompare del) 83 { 84 object max = objects[0]; 85 foreach (var o in objects) 86 { 87 if (del(max, o)) 88 { 89 max = o; 90 } 91 } 92 93 return max; 94 } 95 96 private static bool CompareString(object o1, object o2) 97 { 98 string s1 = o1.ToString(); 99 string s2 = o2.ToString(); 100 return s1.Length < s2.Length; 101 } 102 103 #endregion 104 105 #region 泛型委托 106 107 private static T GetMaxT<T>(T[] ts, Compare<T> compare) 108 { 109 T max = ts[0]; 110 foreach (T t in ts) 111 { 112 if (compare(max, t)) 113 { 114 max = t; 115 } 116 } 117 118 return max; 119 } 120 121 #endregion 122 } 123 }