开发者

Public event of base class in derived class

I have a base-class (let it be SomeBaseClass) containing a public event (SomeEvent) and I have a derived-class in which I want to raise this event but I can't(!!) VS 2010 says me (in derived-class in line: base.SomeEvent != null) "The event 'SomeBaseClass.SomeEvent' can only appear on the left hand side of +开发者_Python百科= or -=". If I replace base on this It is make no sense.


No, it's absolutely right - the event is only an event (with subscription and unsubscription) as far as a derived class is concerned. If your base class wants to let derived classes raise the event, it should include a protected method to do so (typically a virtual OnFoo(EventHandler) for an event called Foo with the EventHandler type, for example). Note that if you write a field-like event in C# like this:

public event EventHandler Foo;

That's actually declaring a private field called Foo (which that class and any nested classes have access to) and a public event (which consists only of subscribe/unsubscribe). You could declare your own "custom" event like this:

protected EventHandler foo;
// Note: not thread-safe. Only present for demonstration purposes.
public event EventHandler Foo
{
    add { foo += value; }
    remove { foo -= value; }
}

and then derived classes would have access to the field... but I wouldn't recommend that. (I rarely declare non-private fields, other than for constants.)


You need to do it the right way (i.e., the idiomatic way in C#)

public class Base {
    public event EventHandler<EventArgs> SomeEvent;
    protected virtual void OnSomeEvent(EventArgs e) {
        EventHandler<EventArgs> handler = SomeEvent;
        if (handler != null) {
            handler(this, e);
        }
    }
}

public class Derived {
    protected virtual void OnSomeEvent(EventArgs e) {
        // derived event handling here
        // then invoke the base handler
        base.OnSomeEvent(e);
    }
}

The reason that you do it like this is because events can only be invoked from within the defining class.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜