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

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

    Well, it's a pattern rather than a rule. It does mean that one component can forward on an event from another, keeping the original sender even if it's not the normal type raising the event.

    I agree it's a bit strange - but it's probably worth sticking to the convention just for familiarity's sake. (Familiarity for other developers, that is.) I've never been particularly keen on EventArgs myself (given that on its own it conveys no information) but that's another topic. (At least we've got EventHandler now - although it would help if there were also an EventArgs for the common situation where you just need a single value to be propagated.)

    EDIT: It does make the delegate more general purpose, of course - a single delegate type can be reused across multiple events. I'm not sure I buy that as a particularly good reason - particularly in the light of generics - but I guess it's something...

提交回复
热议问题