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

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

    You say:

    This leads to lots of event handling code like:-

    RepeaterItem item = sender as RepeaterItem
    if (RepeaterItem != null) { /* Do some stuff */ }
    

    Is it really lots of code?

    I'd advise never to use the sender parameter to an event handler. As you've noticed, it's not statically typed. It's not necessarily the direct sender of the event, because sometimes an event is forwarded. So the same event handler may not even get the same sender object type every time it is fired. It's an unnecessary form of implicit coupling.

    When you enlist with an event, at that point you must know what object the event is on, and that is what you're most likely to be interested in:

    someControl.Exploded += (s, e) => someControl.RepairWindows();
    

    And anything else specific to the event ought to be in the EventArgs-derived second parameter.

    Basically the sender parameter is a bit of historical noise, best avoided.

    I asked a similar question here.

提交回复
热议问题