加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – CA1009:正确声明事件处理程序?

发布时间:2020-12-15 08:07:08 所属栏目:百科 来源:网络整理
导读:我有以下事件,我班级的消费者可以连接以获取内部诊断消息. public event EventHandlerstring OutputRaised; 我用这个函数引发事件 protected virtual void OnWriteText(string e) { var handle = this.OutputRaised; if (handle != null) { var message = st
我有以下事件,我班级的消费者可以连接以获取内部诊断消息.
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声明事件处理程序?我找到的所有答案似乎都不适用于我的场景……只是想了解,我还没有真正掌握事件和代表.

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

解决方法

根据’规则’,EventHandler的type-parameter应该从EventArgs继承:

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.

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

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

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

}

和你的事件处理程序:

public event EventHandler<StringEventArgs> OutputRaised;

当你举起事件时,你应该创建一个StringEventArgs类的实例:

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

我还想补充一点,从理论上讲,你的代码没有任何问题.编译器不会抱怨,您的代码也会起作用. EventHandler< T>委托未指定type参数应从EventArgs继承.它是FxCop,表示您违反了用于声明事件的“设计规则”.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读