private void NotifyFreeChannelsChanged() //1.
{
if (FreeChannelsChanged != null)
{
FreeChannelsChanged(this, null);
}
}
private void NotifyFreeChannelsChanged() //2.
{
NotifyCollectionChangedEventHandler h = FreeChannelsChanged ;
if (h != null)
h(this, e);
}
其中哪个更好,为什么。或者它只是一个额外的支票。区别不大。
最佳答案
“更好”?好吧,不包含(特定的)竞争条件,一个包含。 MultiCastDelegate 类型是不可变的,并且在所有重要的方面都使用值类型语义(它们是引用类型,但是,请参阅this,更重要的是,this),这就是您首先分配它的原因然后检查。问题是:
// this evaluates to true...
if(SomeEvent != null)
{
// ...but before this line executes, the last
// subscriber detached, and now SomeEvent is null. Oops.
SomeEvent(this, e);
}
您应该问“为什么有人会使用示例 #2?”
顺便说一句,这是使用隐式类型变量 (var
) 的好地方。那些委托(delegate)类型名称变长了......
同样有趣的是,竞争条件仍然存在,只是更加微妙。如果订阅者在分配后被删除会怎样?嗯,它仍然会被调用,但实际上(据我所知)你无能为力。
关于c# - 哪种调用事件委托(delegate)的方法更好?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15019744/