6

我有一个 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 属性来测试是否需要发布更新。如果至少其中一个属性发生更改,则保存到数据库。这适用于大多数类型,但集合和列表可以在不使用 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。这是更好的方法吗?我将如何实施?

4

1 回答 1

3

您可以使用事件ObservableCollection<T>寄存器并在CollectionChanged引发事件时标记 IsDirty 标志。

...

ObservableCollection<int> myCollection = new ObservableCollection<int>();
myCollection.CollectionChanged += OnCollectionChanged;

...

public void OnCollectionChanged( Object sender, NotifyCollectionChangedEventArgs e )
{
   IsDirty = true;
}
于 2012-10-12T19:11:53.177 回答