阅读此问题后,似乎以下代码应该失败:
private void Form1_Load(object sender, EventArgs e)
{
EventHandler myHandler = null;
myHandler(this, null);
}
但是当我运行它时,它工作得很好(并且什么都不做)。该代码的行为与以下代码有何不同?
private void Form1_Load(object sender, EventArgs e)
{
EventHandler myHandler = null;
EventHandler myCopy = myHandler;
if (myCopy != null)
{
myHandler(this, null);
}
}
编辑:根据 Lasse V. Karlsen 的回答,以这种方式捕捉异常是有效的:
private void Form1_Load(object sender, EventArgs e)
{
try
{
EventHandler myHandler = null;
myHandler(this, null);
}
catch (Exception ex)
{
this.Text = "Exception!";
}
}