委托(delegate)是一种可以把引用存储为函数的类型。委托声明类似于函数,但不带函数体。且使用delegate关键字。委托的声明指定了一个返回类型和一个参数列表。
class Program
{
delegate double ProcessDelegate(double param1,double 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.WriteLines("Enter 2 numbers separated with a comma:");
string input=Console.ReadLine();
int commaPos=input.IndexOf(','); //IndexOf(',')把括号里的字符位置取出赋给变量commaPos
double param1=Convert.ToDouble(input.Substring(0,commaPos)); //Substring(0,9)把9前面的取出,但不包括第9个
double param2=Convert.ToDouble(input.Substring(commaPos+1,input.Length-commaPos-1));
Console.WriteLines("Enter M to multiply or D to divide:");
input=Console.ReadLine();
if(input==“M”)
process=new processDelegate(Multiply);
else
process=new processDelegate(Divide);
Console.WriteLines("Result:{0}",process(param1,param2));
Console.ReadKey();
}
}