引发事件时出现NullReferenceException

时间:2013-12-21 00:04:38

标签: c# .net wcf events nullreferenceexception

这是错误的代码部分:

JoinAccueilEventArgs jaea = new JoinAccueilEventArgs(this._user);
if (this._user==null)
{
    Console.WriteLine("user...");
}

if (this == null)
{
    Console.WriteLine("this...");
}

if (jaea == null)
{
    Console.WriteLine("jaea...");
}
Console.ReadLine();
JoinAccueilEvent(this, jaea);

我在最后一行获得NullReferenceExceptionJoinAccueilEvent(...) 但是没有任何东西在控制台..

那么这里的null是什么?

internal static event JoinAccueilEventHandler JoinAccueilEvent;
internal delegate void JoinAccueilEventHandler(object sender, JoinAccueilEventArgs e);

private void JoinAccueilHandler(object sender, JoinAccueilEventArgs e)
{
    _callback.UserJoinAccueil(e.User);
}

1 个答案:

答案 0 :(得分:4)

最有可能JoinAccueilEventnull,您应该在使用事件时以典型方式进行检查:

if (JoinAccueilEvent != null)
   JoinAccueilEvent(this, jaea)

问题来自于如果没有人订阅该事件,则为null。您可以通过默认添加 do-nothing 处理程序来解决此问题:

internal static event JoinAccueilEventHandler JoinAccueilEvent = delegate {};

在这种情况下,不需要检查null,因为始终至少有一个事件订阅者。

相关问题