Raise Base Class Events in Derived Classes C#

后端 未结 3 1043
情深已故
情深已故 2021-02-15 07:52

I have a base class DockedToolWindow : Form, and many classes that derive from DockedToolWindow. I have a container class that holds and assigns events to DockedToolWindow objec

相关标签:
3条回答
  • 2021-02-15 08:28

    The difference is scope. Inside your class, you can control how your event delegates are handled, however, your class cannot control what the base class is doing. It might be doing some crazy behind-the-scenes stuff with the event and its handlers. If you simply "reassigned" the Move event, you would be wiping out the multicast delegate list for the event.

    I'm guessing they put a compiler restriction on this because its a very unsafe practice, and would essentially give any descendant class the ability to destroy the event model of its parent.

    0 讨论(0)
  • 2021-02-15 08:33

    You cannot directly fire base class events. This is exactly the reason why you had to make your OnShapeChanged method protected instead of private.

    Use base.OnMove() instead.

    0 讨论(0)
  • 2021-02-15 08:38

    From the C# language spec, section 10.7 (emphasis added):

    Within the program text of the class or struct that contains the declaration of an event, certain events can be used like fields. To be used in this way, an event must not be abstract or extern, and must not explicitly include event-accessor-declarations. Such an event can be used in any context that permits a field. The field contains a delegate (§15) which refers to the list of event handlers that have been added to the event. If no event handlers have been added, the field contains null.

    Thus, the reason you can't treat the Move event like a field is that it is defined in a different type (in this case, your superclass). I agree with @womp's speculation that the designers made this choice to prevent unintended monkeying with the event. It seems obviously bad to allow unrelated types (types not derived from the type declaring the event) to do this, but even for derived types, it might not be desirable. They probably would have had to include syntax to allow the event declaration to be made private or protected with respect to field-style usage, so my guess is that they opted to just disallow it entirely.

    0 讨论(0)
提交回复
热议问题