需求分析:
求数组的最大值无论是int[],string[],类的数组都能够实现
1、声明一个函数可以求数组的最大值
static string GetMax(string[] obj,DelGetMax del)
{
string max =obj[0];
for (int i = 0; i < obj.Length ; i++)
{
if (del(max,obj[i])<0)
{
max = obj[i];
}
}
return max;
}
2、当数组变成int[]时,此方法不在适用,所以把类型改为Object:
static object GetMax(object[] obj,DelGetMax del)
{
object max =obj[0];
for (int i = 0; i < obj.Length ; i++)
{
if (del(max,obj[i])<0)
{
max = obj[i];
}
}
return max;
}
3、if判断时int数组和string数组不一样,所以需要在此处传入一个委托;
声明委托:为判断,所以指定为布尔类型,但是判断有可能存在=0的情况所以让委托返回一个int值和0去比较;
delegate int DelGetMax(object o1,object o2);
4、改进GetMax方法
static object GetMax(object[] obj,DelGetMax del)
{
object max =obj[0];
for (int i = 0; i < obj.Length ; i++)
{
if (del(max,obj[i])<0)
{
max = obj[i];
}
}
return max;
}
5、调用,使用Lamda表达式
static void Main(string[] args)
{
object[] num = { 1, 2, 3, 4, 6, 5, 8, };
object[] str = { "fsdfsfewrwew", "fdsfsdfsdf", "fsfdsfsf", "fdsfsd", "fsd" };
object[] pers = { new Person() { Name = "张三", Age = 23 }, new Person() { Name = "李四", Age = 32 } };
object max1 = GetMax(num,(Object o1,Object o2)=> { return (int)o1 - (int)o2; });
Console.WriteLine(max1);
object max2 = GetMax(str, (object o1, object o2) => { return (o1.ToString().Length - o2.ToString().Length); });
Console.WriteLine(max2);
object max3 = GetMax(pers, (object o1, object o2) => { return ((Person)o1).Age - ((Person)o2).Age; });
Console.WriteLine(((Person)max3).Name);
Console.ReadKey();
6、返回结果