How to factorize events between 2 C# classes since events can only be fired in same class it's defined?
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.
精彩评论