如何PropertyChangedEventHandler工作? [英] how does PropertyChangedEventHandler work?

查看:1847
本文介绍了如何PropertyChangedEventHandler工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个非常简单的问题,但我想知道,如果有人能说明什么四号线实际上是在做什么?因此第一行给出的事件处理程序。我真的不知道在什么情况下处理器将返回null或什么的最后一行呢。

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));
}



我想我用这个来得到这个的code 但我想明白它是什么完全做的事情。

I assume I used this to get this code but I would like to understand what it is doing fully.

推荐答案

如果你只是做:

PropertyChanged(this, new PropertyChangedEventArgs(name))

您会得到一个的NullReferenceException 如果没有人订阅了该事件的的PropertyChanged 。为了解决这个问题,你添加一个空检查:

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))
}

现在,如果你正在使用多-threading有人能空检查和事件的调用之间退订,所以你仍然可以得到一个的NullReferenceException 。为了处理我们的事件处理程序复制到一个临时变量

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));
  }

现在,如果有人从事件退订我们的临时变量处理器仍将指向旧的功能,这些代码现在已经没有扔的NullReferenceException

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.

通常,你会看到人们使用关键字 VAR 来代替,这使得它,所以你并不需要在全类型的临时变量的输入,这是你会看到最常代码的形式

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆