public delegate double Calc(double a, double b);
/// <summary>
/// Define all the concrete calculation
/// </summary>
class Functions
{
public double Add(double a, double b)
{
return a + b;
}
public double Multiply(double a, double b)
{
return a * b;
}
}
/// <summary>
/// Calculator with no concerte calculation.
/// </summary>
class Calculator
{
public Calculator (string Name){}
public double Answer(double a, double b,Calc DelCalc)
{
return DelCalc(a,b);
}
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
Calculator objCalc = new Calculator("Addition");
//instantiate a Functions to handle calculation
Functions objFunctions = new Functions();
//Assign defined function to Calculator delegate
Calc FunAdd = new Calc(objFunctions.Add);
Calc FunMultiply = new Calc(objFunctions.Multiply);
//Calculator can compute using user defined delgete function
Console.WriteLine( objCalc.Answer(312,1231,FunAdd));
Console.WriteLine( objCalc.Answer(312,1231,FunMultiply));
Console.ReadLine();
}
}
}
其中,主程序需要计算两个数相加和相乘,其中定义了一个代理方法Calc,,但这个方法实际上并不做什么,它是用实际的方法objFunctions.add和objFunction.Multiply来实现的,因此,FunAdd和FunMultipy两个实例,都是需要用真正的方法objFunctions.Add和objFunctions.Multiply传入做参数.
然后,Answer的方法就是委托的所在了,主程序需要计算,委托给"中间人"去做,但这个"中间人"实际上是叫Functions类下的方法去真正实施的.所以,可以看到ansewer的参数表里,有Calc DelCalc这个参数.