Posted on 2009-07-29 13:55
Hero 閱讀(186)
評(píng)論(0) 編輯 收藏 引用 所屬分類:
C#積累
/*
* 1. 首先在命名空間中聲明一個(gè)委托 -- 這樣就可以將函數(shù)當(dāng)成一個(gè)對(duì)象來(lái)看待,或者說(shuō)將函數(shù)也當(dāng)成數(shù)據(jù)成員
* 2. 在員工類中定義該委托
* 3. 實(shí)例化聲明的委托
* 4. 委托提高的安全性,同時(shí)也方便了函數(shù)的調(diào)用,委托實(shí)現(xiàn)了將成員函數(shù)數(shù)據(jù)化的用途,這樣就避免了針對(duì)不
* 同的對(duì)象要調(diào)用不同的函數(shù)的麻煩,而只需要在初始化賦值時(shí)指定相應(yīng)的委托實(shí)例
*
*/
using System;
using System.Collections.Generic;
using System.Text;
namespace AnonymousDelegate_Sample
{
// 定義委托方法。
delegate decimal CalculateBonus(decimal sales);
// 定義一個(gè) Employee 類型。
class Employee
{
public string name;
public decimal sales;
public decimal bonus;
public CalculateBonus calculation_algorithm;
}
class Program
{
// 此類將定義兩個(gè)執(zhí)行計(jì)算的委托。
// 第一個(gè)是命名方法,第二個(gè)是匿名委托。
// 首先是命名方法。
// 該方法定義“獎(jiǎng)金計(jì)算”算法的一個(gè)可能實(shí)現(xiàn)。
static decimal CalculateStandardBonus(decimal sales)
{
return sales / 10;
}
static void Main(string[] args)
{
// 獎(jiǎng)金計(jì)算中用到的值。
// 注意:此局部變量將變?yōu)?#8220;捕獲的外部變量”。
decimal multiplier = 2;
// 將此委托定義為命名方法。
CalculateBonus standard_bonus = new CalculateBonus(CalculateStandardBonus);
// 此委托是匿名的,沒(méi)有命名方法。
// 它定義了一個(gè)備選的獎(jiǎng)金計(jì)算算法。
CalculateBonus enhanced_bonus = delegate(decimal sales) { return multiplier * sales / 10; };
// 聲明一些 Employee 對(duì)象。
Employee[] staff = new Employee[5];
// 填充 Employees 數(shù)組。
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;
// 計(jì)算所有 Employee 的獎(jiǎng)金
foreach (Employee person in staff)
PerformBonusCalculation(person);
// 顯示所有 Employee 的詳細(xì)信息
foreach (Employee person in staff)
DisplayPersonDetails(person);
}
public static void PerformBonusCalculation(Employee person)
{
// 此方法使用存儲(chǔ)在 person 對(duì)象中的委托
// 來(lái)進(jìn)行計(jì)算。
// 注意:此方法能夠識(shí)別乘數(shù)局部變量,盡管
// 該變量在此方法的范圍之外。
//該乘數(shù)變量是一個(gè)“捕獲的外部變量”。
person.bonus = person.calculation_algorithm(person.sales);
}
public static void DisplayPersonDetails(Employee person)
{
Console.WriteLine(person.name);
Console.WriteLine(person.bonus);
Console.WriteLine("---------------");
}
}
}