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

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

问题描述

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

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.

搜索诱饵:RSPEC-3906 规则事件处理程序应具有正确的签名"

bait for search: RSPEC-3906 rule "Event Handlers should have the correct signature"

推荐答案

嗯,这是一种模式而不是规则.这确实意味着一个组件可以转发另一个组件的事件,即使它不是引发事件的正常类型,也会保留原始发送者.

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(考虑到它本身不传达任何信息),但这是另一个话题.(至少我们现在有 EventHandler - 尽管如果还有一个 EventArgs 会有所帮助,因为您只需要一个单一的要传播的价值.)

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天全站免登陆