委托方式实现:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace 求任意数组的最大值 { class Program { delegate int CompareDelegate(object o1,object o2); static void Main(string[] args) { object[] array = new object[] {33,22,55,77,11}; object max = GetMax(array,CompareInt); Console.WriteLine(max); object maxStr = GetMax(new object[] { "c", "bbbb", "aa" }, CompareString); Console.WriteLine(maxStr); Console.ReadKey(); } static int CompareInt(object o1, object o2) { int n1 = Convert.ToInt32(o1); int n2 = Convert.ToInt32(o2); return n1 - n2; } static int CompareString(object s1,object s2) { string str1 = s1.ToString(); string str2 = s2.ToString(); return str1.Length - str2.Length; } static Object GetMax(object[] array,CompareDelegate del) { object max = array[0]; for (int i = 1; i < array.Length; i++) { if (del(max,array[i])<0) { max = array[i]; } } return max; } } }
泛型方法实现:(推荐)
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace _02泛型方法实现任意数组的最大值 { delegate int GetMaxDeletate<T>(T t1, T t2); class Program { static void Main(string[] args) { int maxInt = GetMax<int>(new int[] { 3, 55, 11, 77, 333, 27 }, CompareInt); Console.WriteLine(maxInt); Person[] persons = { new Person(){Name="张三",Age =18}, new Person(){Name= "李四",Age= 55} }; Person maxPerson = GetMax<Person>(persons, ComparePerson); Console.WriteLine(maxPerson.Name); Console.ReadKey(); } //比较数组的大小 static int CompareInt(int i1, int i2) { return i1 - i2; } //比较Person对象的大小 static int ComparePerson(Person p1, Person p2) { return p1.Age - p2.Age; } //T 起到占坑的作用 约束数据的类型 static T GetMax<T>(T[] array, GetMaxDeletate<T> del) { T max = array[0]; for (int i = 1; i < array.Length; i++) { if (del(max, array[i]) < 0) { max = array[i]; } } return max; } } class Person { public string Name { get; set; } public int Age { get; set; } } }