[英]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"). 调用OnMessageReceived
,系统将引发System.ArgumentNullException
(“值不能为空。参数名称:类型”)。 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). 但是我找不到这些异常的原因( sender
和e
不为null,请通过调试器进行检查)。
What am I doing wrong ? 我究竟做错了什么 ?
EDIT : Here's my MessageReceivedEventArgs
implementation : 编辑 :这是我的MessageReceivedEventArgs
实现:
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. 任何事件订阅者都有可能引发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. 您也可以尝试通过“ Exception”窗口让ide在每个ArgumentNullException上停止。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.