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

后端 未结 12 797
半阙折子戏
半阙折子戏 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 09:01

    Conventions exist only to impose consistency.

    You CAN strongly type your event handlers if you wish, but ask yourself if doing so would provide any technical advantage?

    You should consider that event handlers don't always need to cast the sender... most of the event handling code I've seen in actual practice don't make use of the sender parameter. It is there IF it is needed, but quite often it isn't.

    I often see cases where different events on different objects will share a single common event handler, which works because that event handler isn't concerned with who the sender was.

    If those delegates were strongly typed, even with clever use of generics, it would be VERY difficult to share an event handler like that. In fact, by strongly typing it you are imposing the assumption that the handlers should care what the sender is, when that isn't the practical reality.

    I guess what you should be asking is why WOULD you strongly type the event handling delegates? By doing so would you be adding any significant functional advantages? Are you making the usage more "consistent"? Or are you just imposing assumptions and constraints just for the sake of strong-typing?

提交回复
热议问题