【委托】C#:委托(delegate)的介绍与使用

一、定义

委托(delegate),即委托别人办事;相当于代理、中介;委托某个方法来实现具体的功能。

委托是一种引用类型,是方法的抽象,声明时与方法相似,但不能称之为方法。

它存储的是一系列具有相同参数和返回类型的方法地址。

调用委托时,委托包含的所有方法都将被执行。

委托在使用时遵循三步走的原则,即定义声明委托实例化委托以及调用委托

二、声明

委托声明决定了可由该委托引用的方法。

语法:

修饰符 delegate 返回值类型 委托名称(参数列表);

例:

public delegate int MyDelegate(string s);

三、实例化委托及使用

一旦声明了委托类型,委托对象必须使用 new 关键字来创建,且与一个特定的方法有关。

创建委托时,传递到new语句的参数就像方法调用一样书写,不带有参数。

实例:

using System;

namespace DelegateApp
{
    delegate int CalculateApp(int a,int b);
    class DelegateTest
    {
        public static int Add(int a,int b)
        {
            return a + b;
        }

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

        static void Main(string[] args)
        {
            CalculateApp cal1 = new CalculateApp(Add);
            CalculateApp cal2 = new CalculateApp(Sub);

            Console.WriteLine("Add value:" + cal1(10, 10));
            Console.WriteLine("Sub value:" + cal2(10, 5));

            Console.ReadKey();
        }
    }
}

执行结果:

Add value:20
Sub value:5

四、委托的组播(也称为多播,Multicasting of a Delegate)

委托对象可以使用 加减 运算符来进行合并或移除;只有相同类型的委托才能被合并。

当委托对象中有多个方法时, 会依次执行委托中的方法,并返回最后一个方法的结果。

using System;

namespace DelegateApp
{
    delegate int CalculateApp(int value);
    class DelegateTest
    {
        static int num = 10;
        public static int Add(int b)
        {
            num += b;
            return num;
        }

        public static int Sub(int b)
        {
            num -= b;
            return num;
        }

        public static int GetNum()
        {
            return num;
        }

        static void Main(string[] args)
        {
            CalculateApp cal;
            CalculateApp cal1 = new CalculateApp(Add);
            CalculateApp cal2 = new CalculateApp(Sub);
            cal = cal1;
            cal += cal2;

            Console.WriteLine("The value of Multicasting:" + GetNum());

            Console.ReadKey();
        }
    }
}

执行结果:

The value of Multicasting:10

委托的基础介绍与使用就到这里啦。

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值