接口侦听器C#,无需订阅

时间:2020-04-21 11:13:32

标签: c# events interface listener

我一直在使用许多API来侦听一些我只需要实现一个接口的事件,但是它不需要我订阅,它们是如何做到的?

为了更好地说明这一点,这是我通常如何做听众

interface IListener
{
    void OnEventHappen();
}

public class EventClass
{
     public static Action onEvent;
}

public class ListenerClass : IListener
{
    //constructor
    public ListenerClass()
    {
         EventClass.onEvent += OnEventHappen;
    }

    //function from IListener interface
    public void OnEventHappen() { //something... }
}

但是在那些API中,不需要在任何地方订阅,我只需要实现这样的接口:(我删除了EventClass,因为在那些API中,我无法访问触发事件的类)

interface IListener
{
    void OnEventHappen();
}

public class ListenerClass : IListener
{
    //function from IListener interface
    public void OnEventHappen() { //something... }
}

1 个答案:

答案 0 :(得分:0)

在c#中,可以使用reflection实现这种行为。

注释中的一个示例提到了Unity及其方法,例如OnBeginDragUpdate。不会使用c#events来调用它们。 Unity主要是用C ++编写的,并且在您的C#代码编译之后,Unity寻找实现某些接口或从某些类继承的所有类(例如MonoBehaviour),并检查它们是否具有匹配的方法(例如Update()),因此它可以稍后在必要时致电给他们。

另一条评论提到Photon,这是Unity常用的网络引擎。在这种情况下,没有“魔术”或反射。要接收Photon的回调,您必须调用PhotonNetwork.AddCallbackTarget方法并将类的实例作为参数传递。事实是,只有在使用Photon时才使人困惑,您不必直接这样做。不必自己调用此方法,您可以继承自MonoBehaviourPunCallbacks类,该类实现了所有Photon的回调接口并在其PhotonNetwork.AddCallbackTarget方法中调用OnEnable。就像我之前解释的那样,该方法又被Unity调用。