简体   繁体   中英

What's the reason of using the Object type instead of an actual type for events?

I am talking about the common signature for events:

Event ( object, args );

and why not:

Event ( ImageProcessor, args );

Is #1 incurs a performance cost too, along with being unclear?

因为一个事件可以由许多不同的对象/类型引发,所以在编译时可能不知道该类型。

I think it's because of historical reasons mixed with avoiding code duplication.

In .Net 1.0 there was no generics, so for each type that can throw event you was forced to define the event handler delegate. like:

public delegate void TextBoxEventHandler(TextBox sender, EventArgs e);
public delegate void ComboBoxEventHandler(ComboBox sender, EventArgs e);

so instead of this, freamework developers created one

public delegate void EventHandler(object sender, EventArgs e);

and used cast/as operators.

From .Net 2.0 we have generics so you can define it once like this

public delegate void EventHandler<TSender, TEventArgs>(TSender sender, TEventArgs e) where TEventArgs: EventArgs;

or even

public delegate void EventHandler<TSender, TEventArgs>(TSender sender, TEventArgs e);

And then use like this.

public event EventHandler<TextBox, string> TextChanged;
public event EventHandler<ComboBox, EventArgs> SomeComboBoxEvent;

But this would break all applications written for .Net 1.0/1.1 so instead framework developers leaved it as it was. And now everyone are using those pre-generics classes.

Also I'm not sure if Windows Forms designer can hadle generic EventHandler. I've never tried to test it.

In my opinion typed (generic) events are better than this standard. So use it where you can.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM