PropertyChangedEventHandler如何工作? [英] how does PropertyChangedEventHandler work?
问题描述
当您传递处理程序时,您的对象和哪个属性更改,它是什么与他们一起?
PropertyChangedEventHandler handler = PropertyChanged; //属性更改是事件
if(handler!= null)
{
handler(this,new PropertyChangedEventArgs(name));
}
我假设我用这个来获取这个代码,但我想了解它在做什么。
如果你刚刚做到:
PropertyChanged这个,新的PropertyChangedEventArgs(name)
你会得到一个 NullReferenceException
如果没有人订阅了事件
PropertyChanged
。为了抵消这一点,你添加一个null检查:
if(PropertyChanged!= null)
{
PropertyChanged (这个,新的PropertyChangedEventArgs(name))
}
现在,如果你使用多线程的人可以取消订阅null检查和调用事件,所以你仍然可以得到一个 NullReferenceException
。为了处理我们将事件处理程序复制到一个临时变量
PropertyChangedEventHandler handler = PropertyChanged;
if(handler!= null)
{
handler(this,new PropertyChangedEventArgs(name));
}
现在如果有人取消订阅我们的临时变量处理程序
仍然会指向旧函数,此代码现在无法抛出 NullReferenceException
。
您通常会看到人们使用关键字 var
,这样就可以使您无需输入临时变量的完整类型,这是您在代码中最常见的形式。
var handler = PropertyChanged;
if(handler!= null)
{
handler(this,new PropertyChangedEventArgs(name));
}
This is a really simple question, but I was wondering if someone could explain what the 4th line is actually doing? so the first line gives an event to the handler. I don't really know in what circumstances handler will return null or what the last line does.
When you pass the handler your object and which property changed, what does it do with them?
PropertyChangedEventHandler handler = PropertyChanged; //property changed is the event
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
I assume I used this to get this code but I would like to understand what it is doing fully.
If you just did:
PropertyChanged(this, new PropertyChangedEventArgs(name))
you would get a NullReferenceException
if no one was subscribed to the event PropertyChanged
. To counteract this you add a null check:
if(PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(name))
}
Now, if you are using multi-threading someone could unsubscribe between the null check and the calling of the event, so you could still get a NullReferenceException
. To handle that we copy the event handler to a temporary variable
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
Now if someone unsubscribes from the event our temporary variable handler
will still point to the old function and this code now has no way of throwing a NullReferenceException
.
Most often you will see people use the keyword var
instead, this makes it so you don't need to type in the full type of the temporary variable, this is the form you will see most often in code.
var handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
这篇关于PropertyChangedEventHandler如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!