如何声明事件处理程序以传递 FxCop 规则,尤其是包含 sender 和 e 的规则?
FxCop 抱怨我的事件处理程序声明。 尽管多次阅读警告,但我不明白代码有什么问题。
我的用户控件中的代码
//This next line Fx Cops doesn't like.
public event ImageClickEventHandler NewEntity; //A thingy defined in the BCL
private void ImgBtnAdd_Click(object sender, ImageClickEventArgs e)
{
NewEntity(sender, e);
}
使用该控件的页面中的
protected override void OnInit(EventArgs e)
{
EntitySearch1.NewEntity += EntitySearch1_NewEntity;
//etc.
}
代码但是 FxCop 说:
按照惯例,.NET 事件有两个参数,分别指定事件发送者和事件数据。 事件处理程序签名应遵循以下形式:void MyEventHandler(object sender, EventArgs e)。 “sender”参数始终为 System.Object 类型,即使可以使用更具体的类型也是如此。 “e”参数始终为 System.EventArgs 类型。 不提供事件数据的事件应使用 System.EventHandler 委托类型。 事件处理程序返回 void,以便它们可以将每个事件发送到多个目标方法。 目标返回的任何值在执行后都会丢失 第一个电话。
FxCop is complaining about a event handler declaration I have. I don't see what is wrong with the code despite reading the warning several times.
Code in my user control
//This next line Fx Cops doesn't like.
public event ImageClickEventHandler NewEntity; //A thingy defined in the BCL
private void ImgBtnAdd_Click(object sender, ImageClickEventArgs e)
{
NewEntity(sender, e);
}
Code in Page that uses the control
protected override void OnInit(EventArgs e)
{
EntitySearch1.NewEntity += EntitySearch1_NewEntity;
//etc.
}
But FxCop says:
By convention, .NET events have two parameters that specify the event sender and event data. Event handler signatures should follow this form: void MyEventHandler(object sender, EventArgs e). The 'sender' parameter is always of type System.Object, even if it is possible to employ a more specific type. The 'e' parameter is always of type System.EventArgs. Events that do not provide event data should use the System.EventHandler delegate type. Event handlers return void so that they can send each event to multiple target methods. Any value returned by a target would be lost after the
first call.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在我看来是假的 - 'e' 参数当然不总是
EventArgs
; 按照惯例,它只是派生自EventArgs
的类型。ImageClickEventArgs
派生自EventArgs
,所以这对我来说看起来不错。 我怀疑 FxCop 过于严格了。Looks bogus to me - the 'e' parameter certainly isn't always
EventArgs
; it's just conventionally a type which derives fromEventArgs
.ImageClickEventArgs
derives fromEventArgs
, so this looks fine to me. I suspect it's FxCop being a little stricter than it should be.根据这篇 msdn 文章,FxCop希望您指定EventHandler
According to this msdn article, FxCop wants you to specify the EventHandler<ImageClickEventArgs>