C# 事件event

public class AAA: MonoBehaviour {

    public delegate void PlayEndDelegate();
    //此处可以使用内置的Action或Func委托简化,
    //具体参考 https://www.cnblogs.com/kingBook/p/5383415.html
    public event PlayEndDelegate playEndEvent;

    private void playEndHandler(){
        playEndEvent();
        //判断是否为null
        //if(playEndEvent!=null)playEndEvent();
        //判断是否为null,还可以简化
        //playEndEvent?.Invoke();
    }

}
public class BBB: MonoBehaviour {
    private AAA _aaa;
    void Start () {
        _aaa=new AAA();
        _aaa.playEndEvent+=onPlayEndHandler;//添加侦听
        _aaa.playEndHandler();
    }

    private void onPlayEndHandler(){
        Debug.Log("bbb onPlayEndHandler");
    }
    
    void OnDestroy(){
        _aaa.playEndEvent-=playEndHandler;//移除侦听
    }
}
//output: bbb onPlayEndHandler

C# 事件event

上一篇:矩阵求导


下一篇:银联SDK