委托的使用

来源:互联网 发布:linux查看jdk环境变量 编辑:程序博客网 时间:2024/05/21 14:03

using System;
using System.Collections.Generic;
using System.Text;
//函数作用:委托的用法
namespace ConsoleApplication21
{
    class Program
    {
        delegate double testDelegate(double x, double y);//创建委托,并且返回值为double

        static double Multiply(double x, double y) //创建函数
        {
            return x * y;
        }

        static double Divide(double x, double y)
        {
            return x / y;
        }

        static void Main(string[] args)
        {
            testDelegate selectAction; //声明
            Console.WriteLine("请输入2个数字!用“,”隔开");
            string getnum = Console.ReadLine();
            int zz = getnum.IndexOf(',');
            double num1 = Convert.ToDouble(getnum.Substring(0,zz));
            double num2 = Convert.ToDouble(getnum.Substring(zz + 1, getnum.Length - zz - 1));
            Console.WriteLine("请选择操作,m or d ");
            string act = Console.ReadLine().ToLower();
            if (act == "m")//这里根据选择初始化委托变量
            { selectAction = new testDelegate(Multiply); }//这里即选择哪个函数执行委托
            else
            { selectAction = new testDelegate(Divide); }
            Console.WriteLine("运算结果:{0}", selectAction(num1,num2));//让委托调用所选函数,并执行
        }
    }
}

原创粉丝点击