using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 求任意数组的最大值
{
class Program
{
//声明委托
public delegate int DelCompare(object o1, object o2);
static void Main(string[] args)
{
//定义一个数组
//object[] o = { 1, 2, 3, 4, 5, 6 };
object[] ostr = { "KobeBryant", "LeBronJames", "KyrieIrving", "KawhiLeonard" };
//委托
//object result = GetMax(o, CompareInt);
//object result = GetMax(ostr, CompareStr);
//匿名函数
//object result = GetMax(ostr, delegate (object o1, object o2)
//{
// //把传过来的两个Object对象转换成int类型
// string str1 = (string)o1;
// string str2 = (string)o2;
// //返回两字符串长度差值
// return str1.Length - str2.Length;
//});
//lamde表达式
object result = GetMax(ostr, (object o1, object o2)=>
{
//把传过来的两个Object对象转换成int类型
string str1 = (string)o1;
string str2 = (string)o2;
//返回两字符串长度差值
return str1.Length - str2.Length;
});
Console.WriteLine("最长的数组是:{0}",result);
Console.ReadKey();
}
//求int类型数组的最大值
public static object GetMax(object[] nums,DelCompare del)
{
object max = nums[0];
for (int i = 0; i < nums.Length; i++)
{
if (del(max, nums[i])<0)
{
max = nums[i];
}
}
return max;
}
public static int CompareInt(object o1,object o2)
{
//把传过来的两个Object对象转换成int类型
int num1 = (int)o1;
int num2 = (int)o2;
//返回两数差值
return num1-num2;
}
//public static int CompareStr(object o1, object o2)
//{
// //把传过来的两个Object对象转换成int类型
// string str1 = (string)o1;
// string str2 = (string)o2;
// //返回两字符串长度差值
// return str1.Length - str2.Length;
//}
}
}
委托.png
网友评论