为什么 .NET 事件具有对象类型而不是 T 类型的发送者参数?
可能的重复:
在 C# 事件处理程序中,为什么必须“sender”参数是一个对象吗?
.NET 中的事件签名 — 使用强类型“发送者”?
为什么 .NET 中的所有事件的第一个参数都是 object
类型,而不是泛型类型 T
?每次我必须获取发件人时,我都必须将其类型转换为某种更派生的类型。例如:
(Button)sender
Possible Duplicates:
In a C# event handler, why must the "sender" parameter be an object?
Event Signature in .NET — Using a Strong Typed 'Sender'?
Why do all of the events in .NET have their first parameter as of type object
, and not of a generic type T
? Every time I have to get my sender, I have to typecast it to some more derived type. For example:
(Button)sender
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
因为事件处理程序方法的通用签名早在泛型被添加到语言中之前就已经发明了。
使用
System.Object
是在泛型出现之前的日子里,这是合乎逻辑的选择,因为它确实是可用的最“通用”的对象。所有其他对象最终都派生自System.Object
,包括控件、BCL 类和用户定义的类,因为它位于类型层次结构的根部。Because the universal signature of event handler methods was invented long before generics were ever added to the language.
Using
System.Object
was the logical choice in the days before generics, as it really was the most "generic" object available. All other objects ultimately derive fromSystem.Object
, including controls, BCL classes, and user-defined classes, because it is at the root of the type hierarchy.强类型发送者不能很好地处理继承层次结构。
现在您想要在
Derived
上订阅MyEvent
。您的发件人将只是Base
。人们可以使用 new 来解决这个问题,但这会变得很难看。Strongly types senders don't work too well with inheritance hierarchies.
Now you want to subscribe on
Derived
toMyEvent
. Your sender will only beBase
. One could work around this withnew
, but that gets ugly.第一个原因是这种设计早于泛型的引入。
但您认为通用方法会是什么样子?在 WinForms 中,OnClick 事件可以由 Button 以及 MenuItem 触发。 MenuItem 甚至不是 Control。
此事件签名在整个 .NET 库中使用,因此发送者实际上可以是任何东西,而不仅仅是 Control 或其他 GUI 元素。最常见的类是...
System.Object
。你必须进行类型转换。
The first reason is that this design pre-dates the introduction of generics.
But what do you think a generic approach would look like? In WinForms an OnClick event can be triggered by a Button as well as by a MenuItem. A MenuItem is not even a Control.
This event signature is used through-out the .NET library, so sender could really be anything, not just a Control or other GUI element. And the mos common class is ...
System.Object
.You will have to type-cast.