Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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);
        }
    }

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.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
439 views
Welcome To Ask or Share your Answers For Others

1 Answer

According to 'the rules', the type-parameter of EventHandler should inherit from 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.

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;
   }

}

and your eventhandler:

public event EventHandler<StringEventArgs> OutputRaised;

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));
    }
}

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...