听起来您希望将状态管理与属性更改通知结合起来。状态管理真的取决于你想怎么做。少数几个有意义的概念是使用对象的备份副本或将原始属性(属性名称)映射到基础字段(属性值)的Dictionary<string, object>。
至于确定是否有任何更改,我将使用 INotifyPropertyChanged 接口。这将使状态管理和通知保持在类内部。只需实现一个名为 OnPropertyChanged(string propName, object propValue) 的包装器(良好实践),它设置一个布尔数组/字典(Dict<string, bool>),然后设置是否有任何更改,如果任何属性发生更改,则 HasChanges 属性返回 true .示例类:
public class TestClass : INotifyPropertyChanged
{
private Dictionary<string, object> BackingStore = new Dictionary<string,object>();
private Dictionary<string, bool> Changes = new Dictionary<string, bool>();
private string _testString;
public string TestString
{
get { return _testString; }
set { _testString = value; OnPropertyChanged("TestString", value); }
}
private bool HasChanges { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
public TestClass(string value)
{
_testString = value;
SaveValues();
}
public void SaveValues()
{
// Expensive, to use reflection, especially if LOTS of objects are going to be used.
// You can use straight properties here if you want, this is just the lazy mans way.
this.GetType().GetProperties().ToList().ForEach(tProp => { BackingStore[tProp.Name] = tProp.GetValue(this, null); Changes[tProp.Name] = false; });
HasChanges = false;
}
public void RevertValues()
{
// Again, you can use straight properties here if you want. Since this is using Property setters, will take care of Changes dictionary.
this.GetType().GetProperties().ToList().ForEach(tProp => tProp.SetValue(this, BackingStore[tProp.Name], null));
HasChanges = false;
}
private void OnPropertyChanged(string propName, object propValue)
{
// If you have any object types, make sure Equals is properly defined to check for correct uniqueness.
Changes[propName] = BackingStore[propName].Equals(propValue);
HasChanges = Changes.Values.Any(tr => tr);
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propName));
}
}
为了简单起见,我只使用 SaveValues/RevertValues 来保存/撤消更改。但是,这些可以很容易地用于实现IEditableObject 接口(BeginEdit、CancelEdit、EndEdit)。然后,PropertyChanged 事件可以通过对象被绑定的任何形式订阅(或者甚至订阅底层 BindingList,这样只需要订阅一个实例),它检查 HasChanges 标志并设置适当的状态表格。