由于您正在尝试跟踪变量是否更改,因此更好的做法是在恕我直言时将您的变量包装在一个可观察的变量中,而不是轮询它。然后,您可以在变量更改时接收事件。当然,您必须更改从变量中读取和写入的方式。
public class ObservableObject<T>
: INotifyPropertyChanging, INotifyPropertyChanged
{
public ObservableObject(T defaultValue = default(T),
IEqualityComparer<T> comparer = null)
{
this.value = defaultValue;
this.comparer = comparer ?? EqualityComparer<T>.Default;
}
private T value;
private IEqualityComparer<T> comparer;
public T Value
{
get { return value; }
set
{
if (!comparer.Equals(this.value, value))
{
OnValueChanging();
this.value = value;
OnValueChanged();
}
}
}
public event PropertyChangingEventHandler PropertyChanging;
protected virtual void OnValueChanging()
{
var propertyChanging = PropertyChanging;
if (propertyChanging != null)
propertyChanging(this, new PropertyChangingEventArgs("Value"));
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnValueChanged()
{
var propertyChanged = PropertyChanged;
if (propertyChanged != null)
propertyChanged(this, new PropertyChangedEventArgs("Value"));
}
}
然后你可以这样做:
var d = new ObservableObject<double>(10);
d.PropertyChanged += (o, e) =>
{
var obs = (ObservableObject<double>)o;
Console.WriteLine("Value changed to: {0}", obs.Value);
};
Console.WriteLine("Value is: {0}", d.Value);
d.Value = 20;
Console.WriteLine("Value is: {0}", d.Value);