简体   繁体   中英

c# event inheritance. Compile but throw an exception at runtime

I've got a problem with an event rising. Here is my base class:

public abstract class MyClass<T>
{
  public event EventHandler<MessageReceivedEventArgs<T>> MessageReceived;

  protected void OnMessageReceived(MyClass<T> sender, MessageReceivedEventArgs<T> e)
  {
    EventHandler<MessageReceivedEventArgs<T>> handler = MessageReceived;

    if (MessageReceived != null)
      MessageReceived(sender, e);
  }
}

And my implementation :

public class MyDerivedClass: MyClass<string>
{
  void AFunction()
  {
    // Do some stuff
    OnMessageReceived(this, new MessageReceivedEventArgs<string>("data"));
  }

When OnMessageReceived is called, the system throw a System.ArgumentNullException ("Value cannot be null. Parameter name: type"). I already read this thread , and this one too, which help me to construct this code. But I can't find the reason of these exception ( sender and e are not null, checked with the debugger).

What am I doing wrong ?

EDIT : Here's my MessageReceivedEventArgs implementation :

public class MessageReceivedEventArgs<T> : EventArgs
{
  public T Data { get; private set; }

  public MessageReceivedEventArgs(T data)
  {
    Data = data;
  }
}

Are you sure the Exception is thrown by your code? It could be possible that any of the event subscribers throws the Exception.

Event handling is a sequential operation. So if the first subscriber throws an unhandled exception the event handling will fail.

Edit: Have you had a look at the stacktrace. Also you could try to let the ide stop on every ArgumentNullException via the "Exception" window.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM