今天看了委托类型(delegate),感觉用法很是神奇,记录下来。
delegate double processDelegate(double param1,param2);
它类似函数,但没有函数体。
再声明两个函数:
static double multiply(double param1,double param2)
{
return param1*param2;
}
static double Divide(double param1,double param2)
{
return param1/param2;
}
主函数中:
static void Main(string[] args)
{
processDelegate process;
Console.WriteLine("Enter 2 numbers separated with a comma");
string input = Console.ReadLine();
int commaPos = input.IndexOf(','); //典型C#用法
double param1 = Convert.ToDouble(input.Substring(0,commaPos));
double param2 = Convert.ToDouble(input.Substring(commaPos+1,input.Length-commaPos-1));
Console.WriteLine("Enter M to multiply or D to divide:");
input = Console.ReadLine();
if (input == "M")
process = new processDelegate(Multiply); //把函数引用赋给委托变量
else
process = new processDelegate(Divide);
Console.WriteLine("Result: {0}",process(param1,param2)); //委托调用所选函数
}