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

查看:203
本文介绍了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;

我提出的情况下使用此功能

I raise the event with this function

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-美国/库/ ms182133.aspx

推荐答案

根据规则,事件处理程序的类型参数应该继承自EventArgs的:

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

事件处理方法需要两个参数。第一类型是   System.Object的,被命名为发件人。这是提出的目标   事件。 第二个参数的类型是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;

当你提高的情况下,你应该offcourse创建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));
    }
}

我也想补充一点,从理论上说,没有什么不对您的code。编译器不抱怨,你的code会工作。该事件处理程序&LT; T&GT; 委托不指定类型参数应该继承 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天全站免登陆