Bestcomy.net blog

Coding for funny

导航

调用自定义event时需要注意的一个问题

Posted on 2006-08-01 15:26  bestcomy  阅读(970)  评论(1编辑  收藏  举报

问题重现
WebForm中定义event
public delegate void AppendFinishedEventHandler(Page sender,SqlTransaction trans);
public event AppendFinishedEventHandler AppendFinished;

激发event
this.AppendFinished(this,trans);

WebForm中通过一个Factory Method 动态Load UserControl.
测试发现WebForm load 某些 UserControl 之后到了激发event的时候抛出了一个NullReferenceException


分析原因
当UserControl 未注册event(AppendFinished)时,AppendFinished 将为null,此时会抛出NullReferenceException
刚发现这个错误的时候一直不明白什么时候AppendFinished 会为null.实际上可以这样想:当Usercontrol并未定义此方法(未注册此event)而去调用,必然会出错。

解决办法
if(this.AppendFinished != null)
 this.AppendFinished(this,trans);