gpt4 book ai didi

c# - IsDirty 标志模式

转载 作者:太空狗 更新时间:2023-10-29 21:51:09 27 4
gpt4 key购买 nike

我有一个包含以下函数的 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;
}
}

在继承基类的类中我用它作为SET对象的包装器,例如:

    public string UserName
{
get { return _userName; }
set { SetField(ref _userName, value); }
}

我使用 IsDirty 属性来测试是否需要发布更新。如果至少有一个属性发生变化,则保存到数据库。这适用于大多数类型,但 Collections 和 Lists 可以在不使用 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;
}
}
}

问题是我现在必须测试 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;
}

但似乎我应该能够想出一个更简洁的解决方案,允许包含 Collection 的类订阅 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;
}

关于c# - IsDirty 标志模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12865425/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com