我想知道是否有'简单'/好方法来检查一个属性是否已经改变。就像在下面的层次结构中,当Child.Name发生变化时(isDirty),我想知道。(有没有)简单的方法来检查(复杂)pocomodel中的属性是否发生了变化?
GrantParent
- Parent
-- Child
在我目前的情况下,我需要浏览模型,看看是否有任何改变。我正在使用IChangeTracking
。
一直在考虑缓存序列化对象的散列。 (太慢了?)
或者创建changedevent哪个调用是父级,直到它到达grantparent。 (健谈?)
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模型。
透明代理。 – jgauffin
能否详细说明一下?我不熟悉透明代理。 (将查找虽然) –
看看这里:http://stackoverflow.com/questions/8580307/handling-propertychanging-propertychanged-via-castles-dynamicproxy – jgauffin