C# delegate委托

Posted carlyin

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C# delegate委托相关的知识,希望对你有一定的参考价值。

委托:存储函数引用类型

     返回类型 和 参数 一致

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Ch06Ex05
{
    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.ReadKey();
        }
    }
}

  为什么不判断参数传入而选择不同函数方法,而非要delegate呢 还要new一个新的delegate类...

 

以上是关于C# delegate委托的主要内容,如果未能解决你的问题,请参考以下文章

c# 委托 delegate

关于js模拟c#的Delegate(委托)实现

C#委托(Delegate)简介

C#委托(Delegate)简介

快速理解C#高级概念 Delegate委托

C# 委托 线程