我想知道是否有'簡單'/好方法來檢查一個屬性是否已經改變。就像在下面的層次結構中,當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