CA1009:正确声明事件处理程序? [英] CA1009: Declare event handlers correctly?

查看:299
本文介绍了CA1009:正确声明事件处理程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下事件,我的班级的消费者可以联系以获取内部诊断消息。

I have the following event that consumers of my class can wire up with to get internal diagnostic messages.

public event EventHandler<string> OutputRaised;

我用这个功能提高事件

protected virtual void OnWriteText(string e)
    {
        var handle = this.OutputRaised;
        if (handle != null)
        {
            var message = string.Format("({0}) : {1}", this.Port, e);
            handle(this, message);
        }
    }

为什么我得到CA1009正确声明事件处理程序?我发现的所有答案似乎不适用于我的场景...只是想了解,我还没有真正把握事件和代表。

Why am I getting CA1009 Declare event handlers correctly? All the answers I found don't seem really applicable to my scenario... Just trying to understand, I don't have a real solid grasp of events and delegates yet.

CA1009上的参考: http://msdn.microsoft.com/en-us /library/ms182133.aspx

Reference on CA1009: http://msdn.microsoft.com/en-us/library/ms182133.aspx

推荐答案

根据规则,EventHandler的类型参数应该继承来自EventArgs:

According to 'the rules', the type-parameter of EventHandler should inherit from EventArgs:


事件处理程序方法有两个参数。第一个类型为
System.Object,名为sender。这是事件引发
的对象。 第二个参数是System.EventArgs类型,
命名为'e'。
这是与事件关联的数据。对于
示例,如果事件在文件打开时被引发,事件
数据通常包含文件的名称。

Event handler methods take two parameters. The first is of type System.Object and is named 'sender'. This is the object that raised the event. The second parameter is of type System.EventArgs and is named 'e'. This is the data that is associated with the event. For example, if the event is raised whenever a file is opened, the event data typically contains the name of the file.

在你的情况下,可能是这样的:

In your case, that could be something like this:

public class StringEventArgs : EventArgs
{
   public string Message {get;private set;}

   public StringEventArgs (string message)
   {
      this.Message = message;
   }

}

和您的事件处理者:

public event EventHandler<StringEventArgs> OutputRaised;

当您提出事件时,您应该离线创建StringEventArgs类的实例:

When you raise the event, you should offcourse create an instance of the StringEventArgs class:

protected virtual void OnWriteText( string message )
{
    var handle = this.OutputRaised;
    if (handle != null)
    {
        var message = string.Format("({0}) : {1}", this.Port, e);
        handle(this, new StringEventArgs(message));
    }
}

我也想补充一点,理论上说你的代码没有错。编译器不会抱怨,你的代码可以工作。 EventHandler< T> 委托没有指定type参数应该继承自 EventArgs
这是FxCop,表示您违反了设计规则来宣布一个事件。

I also would like to add, that theoretically, there's nothing wrong with your code. The compiler doesn't complain and your code will work. The EventHandler<T> delegate does not specify that the type parameter should inherit from EventArgs. It's FxCop that signals that you're violating the 'design rules' for declaring an event.

这篇关于CA1009:正确声明事件处理程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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