C#编程.函数.委托

注:委托最重要的用途最讲到事件和事件处理时才能说清,这里先简单介绍一下关于委托的一些内容

委托是一种可以把引用存储为函数的类型。这听起来相当棘手,但其机制是非常简单的。

1)委托的声明非常类似与函数,但不带函数体,且要使用delegate关键字。委托的声明指定了一个返回类型和一个参数列表。

2)再定义了委托之后,就可以声明发委托类型的变量。接着把这个变量初始化为与委托有相同返回类型和参数列表的函数的引用。

3)之后,就可以使用委托变量调用这个函数,就想该变量是一个函数一样。

示例:

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

namespace TestDelegate
{
    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();
        }
    }
}

执行代码,结果如图所示:


原文地址:https://www.cnblogs.com/haxianhe/p/9271187.html