在C#事件处理程序中,为什么“发件人”参数是一个对象? [英] In a C# event handler, why must the "sender" parameter be an object?

查看:91
本文介绍了在C#事件处理程序中,为什么“发件人”参数是一个对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据 Microsoft事件命名指南 ,C#事件处理程序中的发件人参数是始终类型对象,即使可以使用更具体的类型。

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 more specific type".

这会导致许多事件处理代码,如:

This leads to lots of event handling code like:

RepeaterItem item = sender as RepeaterItem;
if (item != null) { /* Do some stuff */ }

为什么会议建议不要使用更具体的类型声明事件处理程序吗?

Why does the convention advise against declaring an event handler with a more specific type?

MyType
{
    public event MyEventHander MyEvent;
}

...

delegate void MyEventHander(MyType sender, MyEventArgs e);

我错过了吗?


对于后代:我同意大会 使用对象(并通过 EventArgs 即使可以使用更具体的类型,并且在现实世界的编程中, 重要的是遵循惯例。

For posterity: I agree with the general sentiment in the answers that the convention is to use object (and to pass data via the EventArgs even when it is possible to use a more specific type, and in real-world programming it is important to follow the convention.

推荐答案

嗯,这是一种模式,而不是一个规则,这意味着一个组件可以转发另一个事件,保持原始发件人即使不是正常类型提高事件。

Well, it's a pattern rather than a rule. It does mean that one component can forward on an event from another, keeping the original sender even if it's not the normal type raising the event.

我同意这有点奇怪 - 但是,为了熟悉这一点,可能值得坚持约定(熟悉其他开发者,就是这样)我从来没有特别热衷于 EventArgs 我自己(鉴于它自己没有传达任何信息),但这是另一个主题(至少我们有事件处理程序& lt; TEventArgs> - 尽管如果还有一个 EventArgs< TContent> ,那么您只需要一个值即可要传播。)

I agree it's a bit strange - but it's probably worth sticking to the convention just for familiarity's sake. (Familiarity for other developers, that is.) I've never been particularly keen on EventArgs myself (given that on its own it conveys no information) but that's another topic. (At least we've got EventHandler<TEventArgs> now - although it would help if there were also an EventArgs<TContent> for the common situation where you just need a single value to be propagated.)

编辑:它使代理更通用,当然 - 单个委托类型可以跨多个事件重复使用。我不确定我是买这个特别好的原因 - 特别是在泛型的情况下 - 但是我猜这是一些 ...

It does make the delegate more general purpose, of course - a single delegate type can be reused across multiple events. I'm not sure I buy that as a particularly good reason - particularly in the light of generics - but I guess it's something...

这篇关于在C#事件处理程序中,为什么“发件人”参数是一个对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆