<分区>
Possible Duplicate:
Is there a downside to adding an anonymous empty delegate on event declaration?
以下模式在使用事件处理程序(在 C# 中)时非常常见:
public event Action handler;
…
// some method:
if(handler != null) handler();
为这个事件分配一个空委托(delegate)有什么缺点吗?这将在触发事件的任何地方保存 if !=null
条件。当然,这仅适用于我们无法保证始终为事件分配适当委托(delegate)的情况。
public event Action handler;
…
// in constructor:
handler += ()=>{};
…
// some method:
handler();
当然,这对性能有轻微影响,但它使代码更简洁。在这种情况下,最佳做法是什么?有什么技术上的缺点吗?