开发者

C# Custom Event, Inheritance and Closure [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 12 years ago.

Let's say I create a 开发者_如何学编程custom event in c# in some class and broadcast the event including for the class itself. Now how can I create inheritance in that case ? How can I do as if the event was sent to the child class from the same child class instead of sent from parent to parent: is there a way to do this with closure somehow to keep the child context whereas the code will be executed in parent physically due to this inheritance ?


Are you asking how to raise base class event from derived class?
You can't do that directly because event delegate field is private to the class defining it (base class in our case). However you can declare a protected method that raises the event in the base class and call it from derived classes. A commonly used notation suggests to call such method On[EventName] and make it virtual so derived class may intercept (and cancel) event raising:

class Base {
    public event EventHandler Bang;

    protected virtual void OnBang ()
    {
        if (Bang != null)
            Bang (this, EventArgs.Empty);
    }    
}

class Derived : Base {
    public void DoSomething ()
    {
        // let's bang for some fun
        OnBang (); // will raise Bang
    }

    protected override void OnBang ()
    {
        Console.WriteLine ("It's gonna bang now!");
        base.OnBang (); // if we remove this line, event will not be fired
    }
}

Note that you absolutely don't have to override raiser method but I think it's just a better solution to react to own events than to subscribe to them in usual fashion.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜