c# - CA1009 : Declare event handlers correctly?

标签 c# .net events

我有以下事件,我类的消费者可以连接以获取内部诊断消息。

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 声明事件处理程序?我找到的所有答案似乎并不真正适用于我的场景...只是想了解一下,我还没有真正扎实地掌握事件和委托(delegate)。

CA1009 引用:http://msdn.microsoft.com/en-us/library/ms182133.aspx

最佳答案

根据'规则',EventHandler的类型参数应该继承自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}", this.Port, e);
        handle(this, new StringEventArgs(message));
    }
}

我还想补充一点,从理论上讲,您的代码没有任何问题。编译器不会报错,您的代码会正常工作。 EventHandler<T>委托(delegate)没有指定类型参数应该继承自EventArgs . FxCop 表示您违反了声明事件的“设计规则”。

关于c# - CA1009 : Declare event handlers correctly?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27305861/

相关文章:

c# - WPF PasswordBox 到底有多安全?

c# - 使用 C# .NET 进行字符串操作

javascript - IFRAME 上的 onkeydown crossbrowser?

c# - WP7中父列表框垂直滚动时如何锁定水平滚动

c# - 将文本添加到配置文件并在 asp.net 的代码后面使用它

c# - 在 c# listview 中有一列在开头而不是结尾处被截断

.net - 如何在 MSTest 命令行中指定 .runsettings 文件?

c# - 在 c sharp 中广泛使用哈希表

javascript - 如何在内部从事件监听器调用类函数?

eclipse - 在 Eclipse E4 RCP 中使用/测试事件服务的正确方法