我有以下事件,我班级的消费者可以连接以获取内部诊断消息.
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,表示您违反了用于声明事件的“设计规则”.