Delegate?.Invoke();
格式检测委托是否为空,DoAction1与DoAction2等价,但是语法更简单。
using System;
public class Test: MonoBehaviour
{
public Action act;
void Start()
{
//DoAction0(); // NullReferenceException: Object reference not set to an instance of an object
DoAction1();
act = MyAction;
DoAction1();
DoAction2();
}
void DoAction0()
{
act();
}
void DoAction1()
{
if (act != null)
act();
}
void DoAction2()
{
act?.Invoke();
}
void MyAction()
{
Debug.Log("Action");
}
}
来源:CSDN
作者:setsuodu
链接:https://blog.csdn.net/mseol/article/details/104578829