C#委托与回调,用代码详细解释

一、先看看写法

1、委托

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class test2 : MonoBehaviour
{
    //声明委托类型
    private delegate void MyTestDelegate(string data);
    //用委托类型声明委托事件
    private MyTestDelegate myTestEventListener;

    void Awake()
    {
        //为事件添加处理函数
        myTestEventListener += TestEventProcessFunc;
    }

    //为事件的处理函数
    private void TestEventProcessFunc(string data)
    {
        Debug.Log(data);
    }
    void Start()
    {
        myTestEventListener("你好世界");
    }
}


在这里插入图片描述

2、回调

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class test3 : MonoBehaviour
{
    //执行函数,传一个函数作为参数,这个参数就是回调函数
    //<>里面的string,是说这个函数要是接收一个string作为参数的函数
    private void TestFunc(string data, Action<string>action)
    {
        data = "执行函数添加上前缀:" + data;
        action(data);
    }

    //这个是满足上面回调函数格式的函数
    private void myAction(string data)
    {
        Debug.Log(data);
    }


    // Start is called before the first frame update
    void Start()
    {
        TestFunc("你好世界", myAction);
    }
}

在这里插入图片描述

区别:

  1. 从代码上可以看出,一个委托声明的事件用的是+=,也就是说,可以添加很多个委托声明,一旦进行出发,那么将会按照订阅的顺序,也就是+=的顺序进行全部的调用
  2. 从思路上来说,回调就相当于把特定格式的函数当作参数传递,而回调更类似于订阅,用特定格式的委托声明了一个事件,很多符合委托格式的函数都可以进行+=订阅
  3. 委托是根据委托类型来声明事件,而委托类型决定了声明的事件可以由哪些函数来进行订阅,这种思路好像是要比函数会掉路走得更宽,更有层次感。

至于他们在设计上到底有什么微妙的区别,笔者目前还未达到此水平,等到以后理解了,再回来填坑。

猜你喜欢

转载自blog.csdn.net/qq_40666620/article/details/107896358