我有一个包含5个属性的类。
如果将任何值分配给这些字段中的任何一个,则另一个值(例如IsDIrty)将变为true。
public class Class1
{
bool IsDIrty {get;set;}
string Prop1 {get;set;}
string Prop2 {get;set;}
string Prop3 {get;set;}
string Prop4 {get;set;}
string Prop5 {get;set;}
}
最佳答案
为此,您不能真正使用自动获取和 setter ,而需要在每个 setter 中设置IsDirty。
我通常有一个“setProperty”通用方法,该方法采用ref参数,属性名称和新值。
我在 setter 中将此称为``允许我可以设置isDirty的单个点并引发更改通知事件,例如
protected bool SetProperty<T>(string name, ref T oldValue, T newValue) where T : System.IComparable<T>
{
if (oldValue == null || oldValue.CompareTo(newValue) != 0)
{
oldValue = newValue;
PropertyChanged?.Invoke(this, new System.ComponentModel.PropertyChangedEventArgs(name));
isDirty = true;
return true;
}
return false;
}
// For nullable types
protected void SetProperty<T>(string name, ref Nullable<T> oldValue, Nullable<T> newValue) where T : struct, System.IComparable<T>
{
if (oldValue.HasValue != newValue.HasValue || (newValue.HasValue && oldValue.Value.CompareTo(newValue.Value) != 0))
{
oldValue = newValue;
PropertyChanged?.Invoke(this, new System.ComponentModel.PropertyChangedEventArgs(name));
}
}
关于c# - 什么是对对象实现更改跟踪的最佳方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2363801/