Unity委托与事件
1.查找ID和长度最大的车
string GetMaxID(Car[] cars)
{
string Name = "";
int MaxID = 0;
foreach (var item in cars)
{
if (MaxID < item.ID)
{
MaxID = item.ID;
Name = item.NAME;
}
}
return Name;
}
string GetMaxLong(Car[] cars)
{
string Name = "";
int MaxID = 0;
foreach (var item in cars)
{
if (MaxID < item.LONG)
{
MaxID = item.LONG;
Name = item.NAME;
}
}
return Name;
}
string MaxID = GetMaxID(cars);
string MaxLong = GetMaxLong(cars);
两段查找代码中,代码冗余不美观
引入委托
delegate int GetMax(Car cars);
int _ID(Car cars)
{
return cars.ID;
}
int _Long(Car car)
{
return car.ID;
}
string GetMaxSome(Car[] cars, GetMax getMax)
{
string Name = "";
int Max = 0;
foreach (var item in cars)
{
int Temp_Value = getMax(item);
if (Max < Temp_Value)
{
Max = Temp_Value;
Name = item.NAME;
}
}
return Name;
}
GetMaxSome(cars, _Long);
GetMaxSome(cars, _ID);
引入lambda表达式进一步优化
delegate int GetMax(Car cars);
string GetMaxSome(Car[] cars, GetMax getMax)
{
string Name = "";
int Max = 0;
foreach (var item in cars)
{
int Temp_Value = getMax(item);
if (Max < Temp_Value)
{
Max = Temp_Value;
Name = item.NAME;
}
}
return Name;
}
GetMaxSome(cars, car => car.ID);
GetMaxSome(cars, car => car.LONG);
因为_ID 和 _Long 仅使用了一次,所以可以通过lambda表达式代替从而简化代码
|