如何声明事件处理程序以传递 FxCop 规则,尤其是包含 sender 和 e 的规则?

发布于 2024-07-17 13:32:35 字数 789 浏览 5 评论 0原文

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 技术交流群。

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

发布评论

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

评论(2

娜些时光,永不杰束 2024-07-24 13:32:35

在我看来是假的 - '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 from EventArgs.

ImageClickEventArgs derives from EventArgs, so this looks fine to me. I suspect it's FxCop being a little stricter than it should be.

找回味觉 2024-07-24 13:32:35

根据这篇 msdn 文章,FxCop希望您指定EventHandler

According to this msdn article, FxCop wants you to specify the EventHandler<ImageClickEventArgs>

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