Raise Base Class Events in Derived Classes C#

后端 未结 3 1035
情深已故
情深已故 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: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.

提交回复
热议问题