using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Delegate
{
class Program
{
delegate double DelegateProgram(double param1, double param2);//定义一个委托,返回类型和参数列表与Multiply和Divide相同
static double Multiply(double param1,double param2)//两数相乘
{
return param1 * param2;
}
static double Divide(double param1,double param2)//两数相除,暂时忽略除0情况。。。
{
return param1 / param2;
}
static void Main(string[] args)
{
DelegateProgram process;
Console.WriteLine("Enter 2 numbers seperated 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 DelegateProgram(Multiply);//也可以直接写process=Multiply
}
else
{
process = new DelegateProgram(Divide);//同上
}
Console.WriteLine("Result: {0}", process(param1, param2));
}
}
}
c#——委托
最新推荐文章于 2024-01-16 19:42:29 发布