匿名方法:没有名字的方法
Action action = delegate ()//匿名方法函数
{
print("匿名函数被执行");
};
event委托:Event事件本身就是一种委托,只是Event只能作为类的成员(类下一级,与方法平级),且不可在类外或跨类运行event委托;跨类赋方法,只能通过"+=“,而普通Action可以直接”="进行赋方法.
public class MyClass1
{
public event Action eventAction;
public void RunEventAction()
{
if (eventAction != null)
{
eventAction();
}
}
public Action normalAction;
}
public class console : MonoBehaviour {
void Show1()
{
print("Show1方法被执行") ;
}
void Show2()
{
print("Show2方法被执行");
}
void Start () {
MyClass1 myClass = new MyClass1();
myClass.eventAction += Show2; // event跨类赋值只能用多播委托+=或-=
myClass.normalAction = Show1;// 普通赋值可以直接=
myClass.RunEventAction(); //运行event跨类委托只能通过调用目标类的方法,目标类方法中再调用event委托
myClass.normalAction();// 普通委托可以直接调用
}
void Update () {
}
}
多播委托:一个委托中注册多个方法,在注册方法时可以在委托中使用"+“或”-"来实现添加或撤销方法
void Show1()
{
print("Show1方法被执行") ;
}
void Show2()
{
print("Show2方法被执行");
}
void Start () {
Action action = delegate ()//匿名方法函数
{
print("匿名函数被执行");
};
action += Show2; // 多播委托+
action -= Show2;// 多播委托-
if (action != null)
{
action();//如果action最终里面不包含任何方法,则会报错,因为委托属于引用类型,默认为null;所以使用前要先判断委托内方法是否为null
}
}