我正在这样做:
public string FirstName
{
get
{
//Actual Code was doing something to change the value here
this._FirstName = "Hello";
this.OnPropertyChanged("FirstName");
return this._FirstName;
}
set {
if (this._FirstName == value)
return;
this._FirstName = value;
this.OnPropertyChanged("FirstName");
}
}
如您所见,我在 FirstName 属性中提出了 FirstName 属性更改。我原以为这将是一个无限循环,FirstName
getter 将继续调用自己。但奇怪的是并没有发生。
然后我尝试将 raise 属性更改放在里面BackgroundWorker
:
public string _FirstName { get; set; }
public string FirstName
{
get
{
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += (sender, e) =>
{
Thread.Sleep(2000);
};
worker.RunWorkerCompleted += (sender, e) =>
{
this._FirstName = "Hi Hi";
this.OnPropertyChanged("FirstName");
};
worker.RunWorkerAsync();
return this._FirstName;
}
set {
if (this._FirstName == value)
return;
this._FirstName = value;
this.OnPropertyChanged("FirstName");
}
}
好了,这次是无限循环。 但是为什么在第一种情况下没有发生呢?
PS我不是想破坏程序,只是我在调试其他人的程序,他们在这里做的事情就像第一个案例一样。但该物业没有被第二次调用。
更新:测试用例 2 的 StackTrace:
我通过将此属性绑定到 TextBox 并在FirstName
getter 上设置断点来测试它,我可以看到断点被无限次命中。
at Person.get_FirstName()
at RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
at RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at RuntimePropertyInfo.GetValue(Object obj, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture)
at RuntimePropertyInfo.GetValue(Object obj, Object[] index)
at CLRPropertyListener.get_Value()
at PropertyAccessPathStep.get_Value()
at PropertyPathListener.ReconnectPath()
at <>c__DisplayClass4.<BreakOnSharedType>b__3()
at RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder......