大多數時候,當我們使用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事件的臨時對象的確切原因。
這只是一種好的做法,還是還有其他任何好處?
我發現喬恩的答案的答案,並在解釋例如:
Understanding C#: Raising events using a temporary variable
下面是示例代碼來了解這一點:
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;
}
}
看到這篇文章, http://stackoverflow.com/questions/282653/checking-for-null-before-event-dispatching-thread-safe –
見埃裏克利珀關於這個專題的文章,[事件和Races](http://blogs.msdn.com/b/ericlippert/archive/2009/04/29/events-and-races.aspx) – Brian