C# 委托与回调函数(delegate、Action、Func)

1.delegate:

delegate我们常用到的一种声明
Delegate至少0个参数,至多32个参数,可以无返回值,也可以指定返回值类型。
例:public delegate int MethodDelegate(int x, int y);表示有两个参数,并返回int型。

示例代码:

using System;
using UnityEngine;

public class DelegateTest : MonoBehaviour {
    //方法1 定义委托
    public delegate void MethodDelegate (string s);

    void printStr (string s) {
        Debug.Log (s);
    }

    void Start () {
        //方法1 :实例化委托
        MethodDelegate iDelegate = new MethodDelegate (printStr);
        //调用委托
        iDelegate ("1 this is instance delgate");

         //方法2 :直接赋值
        MethodDelegate mDelegate = printStr;
        //调用委托
        mDelegate ("2 this is method delgate");

        //方法3 匿名委托
        MethodDelegate aDelegate = delegate (string s) { Debug.Log (s); };
        aDelegate ("3 this is anonymous delegate");

        //方法4 lambda 表达式
        MethodDelegate lDelegate = (s) => { Debug.Log (s); };
        lDelegate ("4 this is lambda delegate");
    }
}

结果如下:
在这里插入图片描述

2. Action:

Action是无返回值的泛型委托。
Action表示无参,无返回值的委托。
Action<int,string> 表示有传入参数int,string无返回值的委托。
Action<int,string,bool> 表示有传入参数int,string,bool无返回值的委托。
Action至少0个参数,至多16个参数,无返回值。

示例代码:

using System;
using UnityEngine;
public class DelegateAction : MonoBehaviour {
    void Start () {
        Test<string> (Action, "Hello World!");
        Test<int> (Action, 1);
        //lambda 表达式
        Test<string> (p => { Debug.Log( p); }, "Hello World!"); 
    }

    public void Test<T> (Action<T> action, T p) {
        action (p);
    }
    private void Action (string s) {
        Debug.Log(s);
    }
    private void Action (int s) {
        Debug.Log(s);
    }

}

结果如下:
在这里插入图片描述
无参数的回调可以简写为:

void Start () {
    printStr(()=>{
        Debug.Log("zzzzzz");
    });
}

void printStr (Action callback) {
    if (callback != null)
        callback ();
}

3. Func:

Func是有返回值的泛型委托
Func 表示无参,返回值为int的委托
Func<object,string,int> 表示传入参数为object, string 返回值为int的委托
Func<T1,T2,T3,int> 表示传入参数为T1,T2,T3(泛型)返回值为int的委托
Func至少0个参数,至多16个参数,根据返回值泛型返回。必须有返回值,不可void

示例代码:


using System;
using UnityEngine;

public class DelegateEvlove : MonoBehaviour {
   
    void Start () {
        Debug.Log(Test<int, int> (Fun, 1, 2));
        //lambda 表达式
        Debug.Log(Test<int, int> ((a,b)=>{
            return a+b;
        }, 10, 20));
    }

    public int Test<T1, T2> (Func<T1, T2, int> func, T1 a, T2 b) {
        return func (a, b);
    }
    private int Fun (int a, int b) {
        return a + b;
    }
}

结果如下:
在这里插入图片描述;

发布了50 篇原创文章 · 获赞 864 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_28299311/article/details/103041308