2018-07-24【c#】委托 delegate

委托 是 <事件/回调函数> 的基础
1.最简单的委托

image.png
using System;
using System.Collections.Generic;
using System.Text;

namespace Delegate
{
    delegate int NumberChanger(int num);

    class Program
    {
        static int num = 1;

        static void Main(string[] args)
        {
            NumberChanger nm = new NumberChanger(AddNum);
            int a = nm(5);
            Console.WriteLine(a);

            nm = new NumberChanger(DecNum);
            a = nm(5);
            Console.WriteLine(a);

            Console.ReadLine();
        }

        public static int AddNum(int p)
        {
            num += p;
            return num;
        }

        public static int DecNum(int p)
        {
            num -= p;
            return num;
        }
    }
}

2.multicasting delegate
有一个委托列表,按顺序执行,可以加减

using System;
using System.Collections.Generic;
using System.Text;

namespace Delegate
{
    // Muti-casting delegate
    delegate void D(int x);

    class Program
    {

        static void Main(string[] args)
        {
            D fc1 = new D(C.FUNC1);
            fc1(111);

            D fc2 = new D(C.FUNC2);
            fc2(222);

            D fc3 = fc1 + fc2;
            fc3(333);

            Console.ReadLine();
        }
    }

    class C
    {
        public static void FUNC1(int i)
        {
            Console.WriteLine("Func1: " + i);
        }

        public static void FUNC2(int i)
        {
            Console.WriteLine("Func2: " + i);
        }

        public void FUNC3(int i)
        {
            Console.WriteLine("Func3: " + i);
        }
    }
}

3.上述简易写法,直接 += 函数名


image.png

4.事件event
事件是一个修饰符,用来修饰Delegate实例,目的是让这个实例只能在声明该实例的类的内部触发
见下图:

image.png

image.png

image.png
image.png

5.回调函数
回调函数,其实就是通过代理,传递相同格式的函数指针,看了一个例子可以实现一种简单的适配器模式。


image.png

6.Action(无返回值格式代理简化版)/Func(有返回值格式代理简化版)
例:(Ps:Func泛型列表最后一个为返回值类型)
相对于直接调用委托,我更喜欢 .Invoke()方式,这让我能明确知道这是个委托

image.png

7.事件参数,通过lambda表达式,传递到监听者


image.png

image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Swift1> Swift和OC的区别1.1> Swift没有地址/指针的概念1.2> 泛型1.3> 类型严谨 对...
    cosWriter阅读 11,159评论 1 32
  • 1.ios高性能编程 (1).内层 最小的内层平均值和峰值(2).耗电量 高效的算法和数据结构(3).初始化时...
    欧辰_OSR阅读 29,671评论 8 265
  • 1、通过CocoaPods安装项目名称项目信息 AFNetworking网络请求组件 FMDB本地数据库组件 SD...
    阳明AI阅读 16,022评论 3 119
  • 一、Socket又称"套接字” 网络上的两个程序通过一个双向的通信连接实现数据的交换,这个连接的一端称为一个soc...
    阿凡提说AI阅读 145评论 0 0
  • 我再次失眠 /为月亮的清辉/一次次起身 /看天边的浮云 /纳木措的蓝 /洗净我的哀伤 /五千米的山风 /湿润我的双...
    砚砚小屋阅读 429评论 0 0