我想知道是否有一种“简单”/好方法来检查属性是否已更改。就像下面的层次结构中 Child.Name 已更改(isDirty)一样,我想知道。
GrantParent
- Parent
-- Child
在我目前的情况下,我需要浏览模型以查看是否有任何变化。
ps:我正在使用IChangeTracking
.
一直在考虑缓存序列化对象的哈希。(太慢了?)
或者创建调用的父级的changedevent,直到它到达授权父级。(健谈?)
public class Parent: BaseEntity
{
private Child _child;
public Child Child
{
get { return _child; }
set { _child = value; OnPropertyChanged("Child"); }
}
}
public class Child : BaseEntity
{
private int _id;
public int Id {
get { return _id; }
set { _id = value; OnPropertyChanged("Id"); }
}
}
[DataContract]
[Serializable]
public abstract class BaseEntity : INotifyPropertyChanged
{
protected BaseEntity()
{
PropertyChanged += PropertyChangedEventHandler;
}
private void PropertyChangedEventHandler(object sender, PropertyChangedEventArgs e)
{
if (e != null && !String.Equals(e.PropertyName, "IsChanged", StringComparison.Ordinal))
{
this.IsChanged = true;
}
}
protected void OnPropertyChanged<T>(Expression<Func<T>> property)
{
MemberExpression me = property.Body as MemberExpression;
if (me == null || me.Expression != property.Parameters[0]
|| me.Member.MemberType != MemberTypes.Property)
{
throw new InvalidOperationException(
"Now tell me about the property");
}
var handler = PropertyChanged;
if (handler != null) handler(this,
new PropertyChangedEventArgs(me.Member.Name));
}
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool IsChanged
{
get
{
lock (_notifyingObjectIsChangedSyncRoot)
{
return _notifyingObjectIsChanged;
}
}
protected set
{
lock (_notifyingObjectIsChangedSyncRoot)
{
if (!Boolean.Equals(_notifyingObjectIsChanged, value))
{
_notifyingObjectIsChanged = value;
if (IsDirtyChanged != null)
IsDirtyChanged();
this.OnPropertyChanged("IsChanged");
}
}
}
}
private bool _notifyingObjectIsChanged;
private readonly object _notifyingObjectIsChangedSyncRoot = new Object();
public void AcceptChanges()
{
this.IsChanged = false;
}
}
最后,我对已经使用的 XML 序列化程序中的 XML 模型进行了比较。我不需要每秒(左右)一次即时更改检测就足够了。现在我用上次保存后的那个来检查 XML 模型。