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.WriteLine("输入两个数以逗号隔开:"); string input = Console.ReadLine(); int commaPos = input.IndexOf(','); double param1 = Convert.ToDouble(input.Substring(0, commaPos)); double param2 = Convert.ToDouble(input.Substring(commaPos + 1,input.Length - commaPos - 1)); Console.WriteLine("输入 M 进行乘法 或者 D 进行除法:"); input = Console.ReadLine(); if (input == "M") //process = new ProcessDelegate(Multiply); { //委托的第一种写法 process = Multiply; // process(param1, param2); } else //委托的第二种写法 process = new ProcessDelegate(Divide); Console.WriteLine("结果: {0}", process(param1, param2)); Console.ReadKey(); } }
此代码为《C#入门经典》源码有进行学习后,发表到博客里,为提醒以后使用!