抽象类事件c#

时间:2015-05-08 15:49:40

标签: c# abstract-class derived-class

我试图在我的抽象类和派生类中引发事件,让它们在main中出现在同一个事件中。这可能吗?使用下面的代码,我在两个raise事件中设置了一个断点,我看到了bar提升但从未调用foo,并且由于OnDataReceived为null,因此从未调用main中的实际事件。我究竟做错了什么?如果我尝试将bar事件abstract和Raise Function虚拟化为bar并在我的派生类中覆盖它们,那么我会在条形图中的OnDataReceived中得到一个错误,而不是+ =或 - =的左侧。

这基本上就是我所拥有的:

public abstract class bar
{
    public event DataReceivedHandler OnDataReceived;

    protected void RaiseDataReceivedEvent(EventArgs e)
    {
        if (OnDataReceived != null)
            OnDataReceived(this, e);
    }

    /// <summary>
    /// A global event that will happen for all "bar" derived classes
    /// </summary>
    private void globalEvent()
    {
        //Raise this event for the derived class here.
        RaiseDataReceivedEvent(new EventArgs());
    }
}

public class foo : bar
{
    public foo()
    {

    }

    /// <summary>
    /// A specific event that will happen only for this derived class
    /// </summary>
    private void fooSpecificEvent()
    {
        //Raise this event for the derived class here
        RaiseDataReceivedEvent(new EventArgs());
    }
}

public class Main
{
    bar specificProduct = new foo();

    public Main()
    {
        specificProduct.OnDataReceived += specificProduct_OnDataReceived;
    }

    void specificProduct_OnDataReceived(object sender, IttsDataReceivedEventArgs e)
    {
        //Here I want to process events from both fooSpecificEvent and globalEvent calls to RaiseDataReceivedEvent
    }
}

2 个答案:

答案 0 :(得分:0)

您可以将方法GlobalEvent()更改为protected并简单地从foo特定事件中调用它。 这样的事情:

    private void fooSpecificEvent()
{
    //Raise this event for the derived class here
    RaiseDataReceivedEvent(new EventArgs());
    base.globalEvent();
}

答案 1 :(得分:0)

所以,是的......以上代码有效。只需确保调用foo对象与已连接到事件的foo相同。愚蠢的错误。

我有foo_1.OnDataReceived有线,但foo_2是事件调用。