C#中委托用法实例详解
本文实例讲述了C#中委托用法。分享给大家供大家参考。具体分析如下:
这里演示了如何使用匿名委托来计算员工的薪水奖金。使用匿名委托简化了程序,因为无需再定义一个单独的方法。
(-:Thedataforeachemployeeisstoredinanobjectcontainingpersonaldetailsaswellasadelegatethatreferencesthealgorithmrequiredtocalculatethebonus.)=100%(每个员工的数据都存储在一个对象中,该对象中包含了个人的详细信息和一个引用了计算奖金所需算法的委托。:-)通过以委托的方式定义算法,可以使用相同的方法来执行奖金计算,而与实际计算方式无关。另外需要注意的是,一个局部变量multiplier变成了已捕获的外部变量,因为它在委托计算中被引用了。
//版权所有(C)MicrosoftCorporation。保留所有权利。
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Text;
namespaceAnonymousDelegate_Sample
{
//定义委托方法。
delegatedecimalCalculateBonus(decimalsales);
//定义一个Employee类型。
classEmployee
{
publicstringname;
publicdecimalsales;
publicdecimalbonus;
publicCalculateBonuscalculation_algorithm;
}
classProgram
{
//此类将定义两个执行计算的委托。
//第一个是命名方法,第二个是匿名委托。
//首先是命名方法。
//该方法定义“奖金计算”算法的一个可能实现。
staticdecimalCalculateStandardBonus(decimalsales)
{
returnsales/10;
}
staticvoidMain(string[]args)
{
//奖金计算中用到的值。
//注意:此局部变量将变为“捕获的外部变量”。
decimalmultiplier=2;
//将此委托定义为命名方法。
CalculateBonusstandard_bonus=newCalculateBonus(CalculateStandardBonus);
//此委托是匿名的,没有命名方法。
//它定义了一个备选的奖金计算算法。
CalculateBonusenhanced_bonus=delegate(decimalsales){returnmultiplier*sales/10;};
//声明一些Employee对象。
Employee[]staff=newEmployee[5];
//填充Employees数组。
for(inti=0;i<5;i++)
staff[i]=newEmployee();
//将初始值赋给Employees。
staff[0].name="MrApple";
staff[0].sales=100;
staff[0].calculation_algorithm=standard_bonus;
staff[1].name="MsBanana";
staff[1].sales=200;
staff[1].calculation_algorithm=standard_bonus;
staff[2].name="MrCherry";
staff[2].sales=300;
staff[2].calculation_algorithm=standard_bonus;
staff[3].name="MrDate";
staff[3].sales=100;
staff[3].calculation_algorithm=enhanced_bonus;
staff[4].name="MsElderberry";
staff[4].sales=250;
staff[4].calculation_algorithm=enhanced_bonus;
//计算所有Employee的奖金
foreach(Employeepersoninstaff)
PerformBonusCalculation(person);
//显示所有Employee的详细信息
foreach(Employeepersoninstaff)
DisplayPersonDetails(person);
}
publicstaticvoidPerformBonusCalculation(Employeeperson)
{
//此方法使用存储在person对象中的委托
//来进行计算。
//注意:此方法能够识别乘数局部变量,尽管
//该变量在此方法的范围之外。
//该乘数变量是一个“捕获的外部变量”。
person.bonus=person.calculation_algorithm(person.sales);
}
publicstaticvoidDisplayPersonDetails(Employeeperson)
{
Console.WriteLine(person.name);
Console.WriteLine(person.bonus);
Console.WriteLine("---------------");
}
}
}
希望本文所述对大家的C#程序设计有所帮助。