如何使用基类中的事件处理程序

时间:2009-06-29 19:12:33

标签: c# .net event-handling delegates

我是否可以在派生类中使用ChangeHappend。如果是这样的话? 如果没有,我该怎么做呢?

class Base
{
    public delegate void ChangeHandler(object sender);
    public event ChangeHandler ChangeHappend;

    private int _foo;
    public int Foo
    {
        set
        {
            if (_foo == value) return;
            _foo = value;
            ChangeHappend(this);
        }
    }
}

class Derived : Base
{
    private int _bar;
    public int Bar
    {
        set
        {
            if (_bar == value) return;
            _bar = value;
            ChangeHappend(this); // This line gives an error. How can I use ChangeHappend here in Derived?
        }
    }
}

1 个答案:

答案 0 :(得分:9)

使用标准模式:在[EventName]

public class MyBaseClass {
    protected virtual void OnSomethingHappend( EventArgs e ) {
        EventHandler handler = this.SomethingHappend;
        if ( null != handler ) { handler( this, e ); }
    }
    public event EventhHandler SomethingHappend;
}

public MyDerivedClass : MyBaseClass {
    public void DoSomething() {
        this.OnSomethingHappend( EventArgs.Empty );
    }
}