using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1 { //委托: 它把引用存储为函数的类型; 多用于事件及事件的处理; //委托声明不带函数体;使用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.WriteLine("Enter 2 numbers separated with a comma:"); 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("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)); Console.ReadLine(); } } }
时间: 2024-10-11 22:17:35