简体   繁体   English

在接口中声明静态事件并在实现中引发

[英]Declare a static event in an interface and raise in the implementation

public interface IProgress
{
    public static event Action<IProgress> EvtSpawned;
}
public class PlayerSingle : MonoBehaviour, IProgress
{
   
    private void Start()
    {
        IProgress.EvtSpawned?.Invoke(this);
    }
}

I basically want to be able to have some classes listen to whenever an instance is created that implements IProgress.我基本上希望能够在创建实现 IProgress 的实例时监听一些类。 I can subscribe to the event above, but it seems there is no way for me to raise it, it just throws an error even when using within a class that implements IPgrogress.我可以订阅上面的事件,但我似乎没有办法引发它,即使在实现 IPgrogress 的类中使用它也会抛出错误。

For now, I just use static events in classes that implement it one by one.现在,我只是在一个一个实现它的类中使用静态事件。

Events can be invoked only by the "owners" ie IProgress interface in this case.事件只能由“所有者”调用,即本例中的IProgress接口。 Not sure why do you require such structure (the provided description is not enough for me) but if you really need to you can declare an invoke method on the interface to delegate the event invocation:不确定你为什么需要这样的结构(提供的描述对我来说还不够)但是如果你真的需要你可以在接口上声明一个 invoke 方法来委托事件调用:

public interface IProgress
{
    public static event Action<IProgress> EvtSpawned;
    public static void Invoke(IProgress inv) => EvtSpawned?.Invoke(inv);
}

public class PlayerSingle :  IProgress
{
    private void Start()
    {
        IProgress.Invoke(this);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM