c# 求数组的最大值
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _08求数组的最大值 { public delegate int DelCompare(object o1, object o2); class Program { static void Main(string[] args) { object[] nums = { 1, 2, 3, 4, 5, 6, 7 }; object[] names = { "张三", "李FatSoFat shit", "王五" }; object[] pers = { new Person() { Name = "张三", Age = 19 }, new Person() { Name = "李四", Age = 20 }, new Person() { Name = "王五", Age = 22 } }; //object:任意传任意类型 //object[]:只能object类型的数组 //object max = GetMax(nums, C1); //object max = GetMax(names, C2); //object max = GetMax(pers, C3); //Console.WriteLine(((Person)max).Age); //Console.WriteLine(((Person)max).Name); //Console.ReadKey(); object max = GetMax(names, (o1, o2) => { return ((string)o1).Length - ((string)o2).Length; }); Console.WriteLine(max); object max2 = GetMax(pers, (o1, o2) => { return ((Person)o1).Age - ((Person)o2).Age; }); Console.WriteLine(((Person)max2).Name); Console.WriteLine(((Person)max2).Age); Console.ReadKey(); } static object GetMax(object[] nums, DelCompare del)//外面传进来一个比较的方式 { object max = nums[0]; for (int i = 0; i < nums.Length; i++) { //委托 : max-nums[i] if (del(max, nums[i]) < 0)//比较的方式 if(nums[i]>max) { max = nums[i]; } } return max; } //static int C1(object o1, object o2) //{ // int n1 = (int)o1; // int n2 = (int)o2; // return n1 - n2; //} //static int C2(object o1, object o2) //{ // string s1 = (string)o1; // string s2 = (string)o2; // return s1.Length - s2.Length; //} //static int C3(object o1, object o2) //{ // Person p1 = (Person)o1; // Person p2 = (Person)o2; // return p1.Age - p2.Age; //} #region MyRegion //static object GetMax(object[] names) //{ // object max = names[0]; // for (int i = 0; i < names.Length; i++) // { // if (names[i].Length > max.Length) // { // max = names[i]; // } // } // return max; //} //static object GetMax(object[] pers) //{ // object pMax = pers[0]; // for (int i = 0; i < pers.Length; i++) // { // if (pers[i].Age > pMax.Age) // { // pMax = pers[i]; // } // } // return pMax; //} #endregion } class Person { public int Age { get; set; } public string Name { get; set; } } }