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

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

    I think there's a good reason for this convention.

    Let's take (and expand on) @erikkallen's example:

    void SomethingChanged(object sender, EventArgs e) {
        EnableControls();
    }
    ...
    MyRadioButton.Click += SomethingChanged;
    MyCheckbox.Click += SomethingChanged;
    MyDropDown.SelectionChanged += SomethingChanged;
    ...
    

    This is possible (and has been since .Net 1, before generics) because covariance is supported.

    Your question makes total sense if you're going top-down - i.e. you need the event in your code, so you add it to your control.

    However the convention is to make it easier when writing the components in the first place. You know that for any event the basic pattern (object sender, EventArgs e) will work.

    When you add the event you don't know how it will be used, and you don't want to arbitrarily constrain the developers using your component.

    Your example of a generic, strongly typed event makes good sense in your code, but won't fit with other components written by other developers. For instance if they want to use your component with those above:

    //this won't work
    GallowayClass.Changed += SomethingChanged;
    

    In this example the additional type-constraint is just creating pain for the remote developer. They now have to create a new delegate just for your component. If they're using a load of your components they might need a delegate for each one.

    I reckon the convention is worth following for anything external or that you expect to be used outside of a close nit team.

    I like the idea of the generic event args - I already use something similar.

提交回复
热议问题