我有一个BLL的基类,包括以下功能:
public bool IsDirty { get; protected set; }
internal void SetField<TParam>(ref TParam field, TParam value)
{
if (EqualityComparer<TParam>.Default.Equals(field, value) == false)
{
field = value;
IsDirty = true;
}
}
Run Code Online (Sandbox Code Playgroud)
在继承基类的类中,我使用它作为SET对象的包装器,例如:
public string UserName
{
get { return _userName; }
set { SetField(ref _userName, value); }
}
Run Code Online (Sandbox Code Playgroud)
我使用IsDirty属性来测试是否需要发布更新.如果至少有一个属性发生更改,则保存到数据库.这适用于大多数类型,但集合和列表可以在不使用set的情况下更改.我为Collection写了一个包装器,在List上有一个IsDirty标志,可以测试它的变化:
public class CollectionChangeTracked<T> : Collection<T>
{
public bool IsDirty {get; set;}
public CollectionChangeTracked()
{
IsDirty = false;
}
protected override void InsertItem(int index, T newItem)
{
base.InsertItem(index, newItem);
IsDirty = true;
}
protected override void SetItem(int index, T newItem)
{
base.SetItem(index, newItem);
IsDirty = true;
}
protected override void RemoveItem(int index)
{
base.RemoveItem(index);
IsDirty = true;
}
protected override void ClearItems()
{
base.ClearItems();
IsDirty = true;
}
}
}
Run Code Online (Sandbox Code Playgroud)
问题是我现在必须测试Classe的IsDirty属性和任何CollectionChangeTracked.IsDirty标志以进行更新.我可以在一个位置创建执行测试的方法,例如:
public CollectionChangeTracked<ApplicationRole> RolesList
{
get { return _rolesList; }
set { SetField(ref _rolesList, value); }
}
public override bool IsDirty
{
get { return ResolveIsDirty(); }
protected set { _isDirty = value; }
private bool ResolveIsDirty()
{
bool returnValue;
if (_isDirty || RolesList.IsDirty)
returnValue = true;
else
returnValue = false;
return returnValue;
}
Run Code Online (Sandbox Code Playgroud)
但似乎我应该能够提出一个更清晰的解决方案,允许包含Collection的Class订阅CollectionChangeTracked对象的IsDirty更改并根据该更改更新IsDirty.这是更好的方法,我将如何实施?
您可以使用ObservableCollection<T>事件寄存器CollectionChanged并在引发事件时标记 IsDirty 标志。
...
ObservableCollection<int> myCollection = new ObservableCollection<int>();
myCollection.CollectionChanged += OnCollectionChanged;
...
public void OnCollectionChanged( Object sender, NotifyCollectionChangedEventArgs e )
{
IsDirty = true;
}
Run Code Online (Sandbox Code Playgroud)