委托是一个类,它定义了方法的类型,使得可以将方法当作另一个方法的参数来进行传递。

与其他的类不同,委托类具有一个签名,并且它只能对与其签名匹配的方法进行引用

1.语法结构:访问修饰符 delegate 返回类型 委托类型名称(参数列表);

例如:

// 声明一个委托类型,两个参数均为int类型,返回值为int类型
public delegate int Calc(int a, int b);
自定义的委托可以不带参数,也可以没有返回值。

接下来我们看一个例子怎么使用委托

1.方法引用

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

namespace 委托
{
    class Program
    {
        // 声明一个委托类型,两个参数均为int类型,返回值为int类型
        public delegate int Calc(int a, int b);

        // 定义和委托签名一致的方法(参数类型和个数,返回值类型均一致)
        static int Add(int a, int b)
        {
            return a + b;
        }

        static int Sub(int a, int b)
        {
            return a - b;
        }

        static int Multi(int a, int b)
        {
            return a * b;
        }

        static int Divis(int a, int b)
        {
            if (b == 0)
            {
                throw new Exception("除数不能为0!");
            }

            return a / b;
        }

        static void Main(string[] args)
        {
            Console.WriteLine("请输入第一个数:");
            int a = int.Parse(Console.ReadLine());

            Console.WriteLine("请输入第二个数:");
            int b = int.Parse(Console.ReadLine());

            // 定义一个Calc委托类型的变量,把和该委托签名一致的Add方法的引用赋值给变量
            Calc method = Add;
            Console.WriteLine("加法运算:{0}+{1}={2}", a, b, method(a, b));

            method = Sub;
            Console.WriteLine("减法法运算:{0}-{1}={2}", a, b, method(a, b));

            method = Multi;
            Console.WriteLine("乘法运算:{0}×{1}={2}", a, b, method(a, b));

            method = Divis;
            Console.WriteLine("除法运算:{0}÷{1}={2}", a, b, method(a, b));

            Console.ReadKey();
        }
    }
}
(1)方法引用

相关文章:

  • 2021-07-05
  • 2021-06-19
  • 2021-12-28
  • 2022-03-06
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-06-15
  • 2022-12-23
  • 2021-08-25
  • 2021-04-26
  • 2021-09-22
相关资源
相似解决方案