根据Microsoft 事件命名指南 https://msdn.microsoft.com/en-us/library/h0eyck3s%28VS.71%29.aspx, the sender
C# 事件处理程序中的参数“是always类型对象,即使可以使用更具体的类型”。
这导致了许多事件处理代码,例如:
RepeaterItem item = sender as RepeaterItem;
if (item != null) { /* Do some stuff */ }
为什么约定建议不要声明具有更具体类型的事件处理程序?
MyType
{
public event MyEventHander MyEvent;
}
...
delegate void MyEventHander(MyType sender, MyEventArgs e);
我错过了一个陷阱吗?
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 规则“事件处理程序应具有正确的签名”
嗯,这是一种模式而不是规则。这确实意味着一个组件可以转发来自另一个组件的事件,从而保留原始发送者,即使它不是引发事件的正常类型。
我同意这有点奇怪 - 但为了熟悉而遵守惯例可能是值得的。 (即其他开发人员的熟悉程度。)我从来没有特别热衷于EventArgs
我自己(鉴于它本身不传达任何信息)但那是另一个话题。 (至少我们有EventHandler<TEventArgs>
现在 - 虽然如果还有一个的话会有帮助EventArgs<TContent>
对于只需要传播单个值的常见情况。)
编辑:当然,它确实使委托更加通用 - 单个委托类型可以在多个事件中重用。我不确定我购买它是一个特别好的理由 - 特别是考虑到仿制药 - 但我想这是某物...
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)