委托事件在 设计模式---观察者模式 中应用很广泛,想了解观察者模式如何使用可以看我下一篇贴:https://blog.csdn.net/weixin_55532142/article/details/124390719?spm=1001.2014.3001.5502
我们可以这样理解委托:委托可以把“方法”当做“参数”来传递。往下再看会儿就知道了。
常见的类型有string,int,float,这些都是类型,那“方法”就是委托类型。
委托的语法:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
访问修饰符 delegate 返回值类型 委托名称(参数列表);
public delegate void ShowDelegate(); //无参.
public delegate void NameDelegate(string info); //一个参数.
public delegate void hpDelegate(int value);
public class LambdaDemo : MonoBehaviour
{
public ShowDelegate ShowDel;
public NameDelegate NameDel;
public event hpDelegate HPDel; //这个是事件.
void Start()
{
ShowDel = Ptong;
//横着写,隔行写都行,方便对比我就写2个版本了.
//ShowDel += delegate () { Debug.Log("匿名方法"); };
ShowDel += delegate ()
{
Debug.Log("匿名方法");
};
//没有参数时,必须写().
//ShowDel += () => { Debug.Log("Lambda表达式方法"); };
ShowDel += () =>
{
Debug.Log("Lambda表达式方法");
};
//NameDel = (string info) => { Debug.Log("Lambda表达式方法" + info); };
NameDel = (string info) =>
{
Debug.Log("Lambda表达式方法" + info);
};
//只有一个参数时,可以不写“类型”与“()”.
//NameDel += info => { Debug.Log("Lambda表达式方法精简" + info); };
NameDel += info =>
{
Debug.Log("Lambda表达式方法精简" + info);
};
//方法体只有一句话的时候,可以不用写“{}”.
NameDel += info => Debug.Log("Lambda表达式方法精简升级版" + info);
ShowDel();
NameDel("一个参数");
}
void Ptong()
{
Debug.Log("普通方法");
}
}
delegate就是 委托 的关键字,委托方法可以在类里面定义,也可以在类外面定义,建议在类外面定义方便其他脚本使用。
我在类外面定义了2个委托方法,在类里面定义了2个委托方法类型的 字段,而这2个 字段本质上就是“方法”。其实这样就已经完成了委托方法的定义了。
多播委托:
其实就是委托链,可以传递(绑定)很多个“方法”到一个委托方法里面,按照赋值顺序执行。
在一个脚本里面进行 委托变量赋值,
第一次要使用 “=”,
第二次往后都要使用 “+=”,
如果后续还用 “=” 的话,之前赋值存储在 委托方法 里的 “方法”都会丢失,相当于重置;
移除某个方法:使用 “-=”;
事件:
public event hpDelegate HPDel;
在委托类前加上event关键字就是事件了。
在外部访问的时候,事件比委托更安全(不能用 “=”)。
C#内置委托:
使用的时候要先引入命名空间using System;
Action 是无参无返回值的内置委托类型;
当我们需要用到该类型(无参无返回值)的委托的时候,就不需要再自己定义了,
我们可以直接使用该类型声明委托变量。
Func 是无参有返回值的内置委托类型;
Func 和 Action 对比:Action 都是无返回值的,Func 都是有返回值的。
具体选择哪个使用,就看你是否需要返回值。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class FuncDemo : MonoBehaviour
{
public Func<int> funcDel;
public Func<int, int, int> funcCalc;
void Start()
{
//funcDel = () => { return 550; };
//funcDel = () =>
//{
// Debug.Log("晚上好");
// return 600;
//};
//int temp = funcDel();
//Debug.Log(temp);
funcCalc = (int a, int b) => { return a + b; };
funcCalc += (a, b) => a * b;
Debug.Log(funcCalc(2, 5));
}
}