大多数情况下,当我们使用 MVVM 时,我们使用 INotifyPropertyChanged 接口向绑定提供通知,一般实现如下所示:
public class MyClass : INotifyPropertyChanged
{
// properties implementation with RaisePropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
每当我阅读专家的代码时,这对我来说都很好 - 他们编写了类似的代码:
public class MyClass : INotifyPropertyChanged
{
// properties implementation with RaisePropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(string propertyName)
{
var tempchanged = PropertyChanged;
if (tempchanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
我想知道为 PropertyChanged 事件创建临时对象的确切原因是什么。
这只是一个好的做法还是有任何其他相关的好处?
我在乔恩的回答和解释的例子中找到了答案:
这是理解这一点的示例代码:
using System;
using System.Collections.Generic;
using System.Threading;
class Plane
{
public event EventHandler Land;
protected void OnLand()
{
if (null != Land)
{
Land(this, null);
}
}
public void LandThePlane()
{
OnLand();
}
}
class Program
{
static void Main(string[] args)
{
Plane p = new Plane();
ParameterizedThreadStart start = new ParameterizedThreadStart(Run);
Thread thread = new Thread(start);
thread.Start(p);
while (true)
{
p.LandThePlane();
}
}
static void Run(object o)
{
Plane p = o as Plane;
while (p != null)
{
p.Land += p_Land;
p.Land -= p_Land;
}
}
static void p_Land(object sender, EventArgs e)
{
return;
}
}