In a C# event handler, why must the “sender” parameter be an object?

后端 未结 12 806
半阙折子戏
半阙折子戏 2020-12-02 08:19

According to Microsoft event naming guidelines, the sender parameter in a C# event handler \"is always of type object, even if it is possible to use a

12条回答
  •  一个人的身影
    2020-12-02 08:53

    Generics and history would play a big part, especially with the number of controls (etc) that expose similar events. Without generics, you would end up with a lot of events exposing Control, which is largely useless:

    • you still have to cast to do anything useful (except maybe a reference check, which you can do just as well with object)
    • you can't re-use the events on non-controls

    If we consider generics, then again all is well, but you then start getting into issues with inheritance; if class B : A, then should events on A be EventHandler, and events on B be EventHandler? Again, very confusing, hard for tooling, and a bit messy in terms of language.

    Until there is a better option that covers all of these, object works; events are almost always on class instances, so there is no boxing etc - just a cast. And casting isn't very slow.

提交回复
热议问题