为什么 .NET 事件具有对象类型而不是 T 类型的发送者参数?

发布于 2024-11-29 06:42:27 字数 522 浏览 0 评论 0原文

可能的重复:
在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

老子叫无熙 2024-12-06 06:42:27

因为事件处理程序方法的通用签名早在泛型被添加到语言中之前就已经发明了。

使用 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 from System.Object, including controls, BCL classes, and user-defined classes, because it is at the root of the type hierarchy.

萌吟 2024-12-06 06:42:27

强类型发送者不能很好地处理继承层次结构。

public class Base
{
  public event EventHandler<Base,MyEventArgs> MyEvent;
}

public class Derived:Base
{

}

现在您想要在 Derived 上订阅 MyEvent。您的发件人将只是Base。人们可以使用 new 来解决这个问题,但这会变得很难看。

Strongly types senders don't work too well with inheritance hierarchies.

public class Base
{
  public event EventHandler<Base,MyEventArgs> MyEvent;
}

public class Derived:Base
{

}

Now you want to subscribe on Derived to MyEvent. Your sender will only be Base. One could work around this with new, but that gets ugly.

jJeQQOZ5 2024-12-06 06:42:27

第一个原因是这种设计早于泛型的引入。

但您认为通用方法会是什么样子?在 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文