C#中委托用法实例详解


本文实例讲述了C#中委托用法。分享给大家供大家参考。具体分析如下:

这里演示了如何使用匿名委托来计算员工的薪水奖金。使用匿名委托简化了程序,因为无需再定义一个单独的方法。
(-:The data for each employee is stored in an object containing personal details as well as a delegate that references the algorithm required to calculate the bonus.)=100%(每个员工的数据都存储在一个对象中,该对象中包含了个人的详细信息和一个引用了计算奖金所需算法的委托。:-) 通过以委托的方式定义算法,可以使用相同的方法来执行奖金计算,而与实际计算方式无关。另外需要注意的是,一个局部变量 multiplier 变成了已捕获的外部变量,因为它在委托计算中被引用了。

// 版权所有 (C) Microsoft Corporation。保留所有权利。
using System;
using System.Collections.Generic;
using System.Text;
namespace AnonymousDelegate_Sample
{
  // 定义委托方法。
  delegate decimal CalculateBonus(decimal sales);
  // 定义一个 Employee 类型。
  class Employee
  {
    public string name;
    public decimal sales;
    public decimal bonus;
    public CalculateBonus calculation_algorithm;
  }
  class Program
  {
    // 此类将定义两个执行计算的委托。
    // 第一个是命名方法,第二个是匿名委托。
    // 首先是命名方法。
    // 该方法定义“奖金计算”算法的一个可能实现。
    static decimal CalculateStandardBonus(decimal sales)
    {
      return sales / 10;
    }
    static void Main(string[] args)
    {
      // 奖金计算中用到的值。
      // 注意:此局部变量将变为“捕获的外部变量”。
      decimal multiplier = 2;
      // 将此委托定义为命名方法。
      CalculateBonus standard_bonus = new CalculateBonus(CalculateStandardBonus);
      // 此委托是匿名的,没有命名方法。
      // 它定义了一个备选的奖金计算算法。
      CalculateBonus enhanced_bonus = delegate(decimal sales) { return multiplier * sales / 10; };
      // 声明一些 Employee 对象。
      Employee[] staff = new Employee[5];
      // 填充 Employees 数组。
      for (int i = 0; i < 5; i++)
        staff[i] = new Employee();
      // 将初始值赋给 Employees。
      staff[0].name = "Mr Apple";
      staff[0].sales = 100;
      staff[0].calculation_algorithm = standard_bonus;
      staff[1].name = "Ms Banana";
      staff[1].sales = 200;
      staff[1].calculation_algorithm = standard_bonus;
      staff[2].name = "Mr Cherry";
      staff[2].sales = 300;
      staff[2].calculation_algorithm = standard_bonus;
      staff[3].name = "Mr Date";
      staff[3].sales = 100;
      staff[3].calculation_algorithm = enhanced_bonus;
      staff[4].name = "Ms Elderberry";
      staff[4].sales = 250;
      staff[4].calculation_algorithm = enhanced_bonus;
      // 计算所有 Employee 的奖金
      foreach (Employee person in staff)
        PerformBonusCalculation(person);
      // 显示所有 Employee 的详细信息
      foreach (Employee person in staff)
        DisplayPersonDetails(person);
    }
    public static void PerformBonusCalculation(Employee person)
    {
      // 此方法使用存储在 person 对象中的委托
      // 来进行计算。
      // 注意:此方法能够识别乘数局部变量,尽管
      // 该变量在此方法的范围之外。
      //该乘数变量是一个“捕获的外部变量”。
      person.bonus = person.calculation_algorithm(person.sales);
    }
    public static void DisplayPersonDetails(Employee person)
    {
      Console.WriteLine(person.name);
      Console.WriteLine(person.bonus);
      Console.WriteLine("---------------");
    }
  }
}

希望本文所述对大家的C#程序设计有所帮助。


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3