[英]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? #1是否还会带来性能成本以及不清楚?
因为一个事件可以由许多不同的对象/类型引发,所以在编译时可能不知道该类型。
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. 在.Net 1.0中,没有泛型,因此对于每种可能引发事件的类型,您都必须定义事件处理程序委托。 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 因此,与此相反,freamework开发人员创建了一个
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 从.Net 2.0开始,我们有了泛型,因此您可以像这样定义一次
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. 但这将破坏为.Net 1.0 / 1.1编写的所有应用程序,因此框架开发人员将其保留了原样。 And now everyone are using those pre-generics classes.
现在每个人都在使用这些泛型类。
Also I'm not sure if Windows Forms designer can hadle generic EventHandler. 另外我不确定Windows窗体设计器是否可以使用通用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.
因此,请尽可能使用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.