开发者

How to factorize events between 2 C# classes since events can only be fired in same class it's defined?

开发者 https://www.devze.com 2023-02-28 02:45 出处:网络
Let\'s say I have for class A and class B: public event开发者_JS百科 CustomEvent1 event1 public event CustomEvent2 event2

Let's say I have for class A and class B:

public event开发者_JS百科 CustomEvent1 event1
public event CustomEvent2 event2

How can I create a class C which A & B would inherit the events since events can only be fired in same class it's defined ?


In this case you should define in class C a method like

protected void OnEventName(object sender, EventArgs e)
{
    CustomEventC evt = EventC;
    if (evt != null)
        evt(this, EventArgs.Empty);
}

Since it is a protected method, it will be visible from classes A and B.


Refer to Calling C# events from outside the owning class?


Make an OnCustomEvent method in the C class that calls the event. Then you can call the method from the A and B classes.

You can look in the framework in any webform or winform control that uses events for an example of this solution.

0

精彩评论

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