c# 委托笔记

简单的委托:

当建立委托对象时,委托的参数类型必须与委托方法相对应。只要向建立委托对象的结构函数中输入方法名称mm.Method,委托就会直接绑定此方法。使用my.Invoke(string message),就能显示调用委托方法。但在实际的操作中,无须用到Invoke方法,而只要直接使用myDelegate(string message),就能调用委托方法。


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

namespace ConsoleApplication21
{
    class Program
    {
        delegate void MyDelegate(string message);

        public class Example
        {
            public void Method(string message)
            {
                Console.WriteLine(message);
            }
        }

        static void Main(string[] args)
        {
            Example mm = new Example();
            MyDelegate my = new MyDelegate(mm.Method);
            my("hello world");
            Console.ReadKey();
        }
    }
}



带返回值得委托:

当建立委托对象时,委托的返回值必须与委托方法相对应。

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

namespace ConsoleApplication21
{
    class Program
    {
        delegate string MyDelegate(string message);

        public class Example
        {
            public string otherMethod(string message)
            {
                return "hello" + message;
            }
        }

        static void Main(string[] args)
        {
            Example mm = new Example();
            MyDelegate my = new MyDelegate(mm.otherMethod);
            string ss = my("Ding");
            Console.WriteLine(ss);
            Console.ReadKey();
        }
    }
}

多路广播委托:

委托继承于MulticastDelegate,这使委托对象支持多路广播,即委托对象可以绑定多个方法。当输入参数后,每个方法会按顺序进行迭代处理,并返回最后一个方法的计算结果。

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

namespace ConsoleApplication21
{
    class Program
    {
        delegate double MyDelegate(double price);

        public class Example
        {
            public double Method(double price)
            {
                double price1 = price * 0.9;
                Console.WriteLine("price1 = " + price1);
                return price1;
            }
            public double otherMethod(double price)
            {
                double price2 = price * 0.85;
                Console.WriteLine("price2 = " + price2);
                return price2;
            }
        }

        static void Main(string[] args)
        {
            Example mm = new Example();
            MyDelegate my = new MyDelegate(mm.Method);
            my = my + mm.otherMethod;
            Console.WriteLine("lastPrice = "+ my(100));
            Console.ReadKey();
        }
    }
}




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值