C# delegate,Action,Func,Event 使用

1. delegate 委托

作用:
(1)将方法当作参数传递
(2)方法的一种多态(类似于一个方法模板,可以匹配很多个方法)
(3)声明:访问修饰符 delegate 返回值类型 委托名(参数列表)
(4)添加和移除:+=,-=

public class DelegateTest : MonoBehaviour
{
    public delegate int MyDelegate(int x, int y);
    public delegate void MyVoidDelegate(int x);

    // 与委托匹配的一个方法
    public int Add(int a, int b) 
    {
        return a + b;
    }

    // 与委托匹配的另一个方法
    public int Reduce(int a, int b)
    {
        return a - b;
    }

    // 示例:将委托当参数传递
    public int Test(MyDelegate md, int a, int b)
    {
        return md(a, b);
    }

    public void Method1(int a)
    {
        Debug.Log($"a={a}");
    }

    public void Method2(int b)
    {
        Debug.Log($"b={b}");
    }

    void Start()
    {
        /*** 一般用法 ***/
        // MyDelegate md = new MyDelegate(Add);  // 第一种种初始化方式
        MyDelegate md;                           // 第二种种初始化方式
        md = Add;
        int resultA = md(2, 3);
        md = Reduce;
        int resultB = md(5, 4);
        int resultC = Test(md, 4, 4); // 传的是 Reduce 方法

        Debug.Log($"{resultA}, {resultB}, {resultC}"); // 打印: 5, 1, 0

        /*** 多播 ***/
        MyVoidDelegate md1 = null;
        md1 += Method1;
        md1 += Method2;
        md1(12);    // 打印: a=12 b=12

        /*** 有返回值的多播问题 ***/
        MyDelegate md2 = null;
        md2 += Add;
        md2 += Reduce;
        int resultD = md2(1, 1);  
        Debug.Log(resultD); // 打印: 0(只返回最后一个方法的返回值)
    }
}

2. Event 事件

(1)事件 event 是一种具有特殊签名的委托
(2)添加和移除:+=,-=
(3)访问修饰符 event 委托类型 事件名

public class DelegateTest : MonoBehaviour
{
    public delegate void MyVoidDelegate(int x);
    public event MyVoidDelegate myEvent;

    public void Method1(int a)
    {
        Debug.Log($"a={a}");
    }

    public void Method2(int b)
    {
        Debug.Log($"b={b}");
    }

    void Start()
    {
        myEvent = Method1;
        myEvent += Method2;
        myEvent += (int c) => {Debug.Log($"c={c}");};
        myEvent(10);    // 打印:a=10 b=10 c=10
    }
}

3. Action 无返回值委托

可带参,无返回值委托

public class DelegateTest : MonoBehaviour
{
    public void Method1(int a)
    {
        Debug.Log($"a={a}");
    }

    void Start()
    {
        Action<int> action;
        action = (int a) => {Debug.Log(a);};
        action += Method1;
        action(10); // 打印:10 a=10
    }
}

4. Func 带返回值委托

public class DelegateTest : MonoBehaviour
{
    public void Method1(int a)
    {
        Debug.Log($"a={a}");
    }

    void Start()
    {
        Func<int, int, int> func = null;   // 带两个 int 参数,返回一个 int 参数
        func += (int a, int b) => a + b;
        int result = func(1, 2);
        Debug.Log(result);  // 打印:3
    }
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值