简体   繁体   English

使用接口事件引发继承

[英]using an interface event throw inhertance

for the following code: 对于以下代码:

delegate void deffault ();

public interface IBoom {
    event deffault OnBoom; 
}

public class BoomObject : IBoom {

    public event deffault OnBoom;

    public virtual void Start () {

    }

}

public class Grenade : BoomObject {

    public override void Start () {
        if (OnBoom != null)
            OnBoom ();
    }

}

I'm trying to Invoke an event in the base class throw a sub class, I don't know why it throw exception or if this is a good practice or not. 我试图在基类中调用一个事件引发一个子类,我不知道为什么它引发异常,或者这是否是一个好习惯。

the exception I get is : 我得到的例外是:

The event BoomObject.OnBoom' can only appear on the left hand side of += or -= when used outside of the type BoomObject' 当事件BoomObject.OnBoom' can only appear on the left hand side of += or -= when used outside of the type BoomObject' BoomObject.OnBoom' can only appear on the left hand side of += or -= when used outside of the type左侧。

This is not an exception, this is a compiler error. 这不是例外,这是编译器错误。

The problem is that events implemented by public event DelegateType Event; 问题在于事件由public event DelegateType Event; can only be raised in the class that defines the event, not any derived class. 只能在定义事件的类中引发,而不能在任何派生类中引发。

If you want to make this event accessible to derived classes, implement a protected RaiseEvent() method in your case class: 如果要使派生类可以访问此事件,请在案例类中实现一个受保护的RaiseEvent()方法:

public class BoomObject : IBoom {
    public event deffault OnBoom;

    protected void RaiseBoom() {
         if (OnBoom != null)
             OnBoom ();
    }

    public virtual void Start () {
    }
}

public class Grenade : BoomObject {
    public override void Start () {
        RaiseBoom();
    }
}

You're not getting an exception but a syntax error from the compiler. 您没有收到异常,但是编译器出现语法错误。 Let us see what it says 让我们看看它怎么说

The event BoomObject.OnBoom' can only appear on the left hand side of += or -= when used outside of the typeBoomObject 当在typeBoomObject之外使用时,事件BoomObject.OnBoom'只能出现在+ =或-=的左侧

Okay so it tells you that you can only use -= or += for some reason. 好的,它告诉您由于某些原因只能使用-=+= And that reason is that you are trying something outside the class where the event was declared. 那是因为您正在尝试在声明该事件的类之外进行某些操作。 That is on purpose. 那是故意的。 Events can only be raised within the declaring class. 事件只能在声明类中引发。

So to raise the event you have to eg create a method in the base class and call it in the derived class. 因此,要引发事件,您必须例如在基类中创建一个方法并在派生类中调用它。

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

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