2015-11-30 48 views
0

我想创建一个业务对象集合类(List of T)。我的业务对象有一个Deleted属性(所以我可以跟踪DB的删除)。集合类需要覆盖List的remove,for-each枚举方法等,以便我可以将业务对象标记为已删除,而不是从列表中“物理”删除,并在枚举期间跳过它们。到目前为止,我有一个继承List(BusObject)的类,但是我发现一些List方法(即Remove)不能被覆盖。我接近这个错误吗?也许我不应该继承List并使用我自己的方法在内部管理列表?.NET业务对象集合(列表)

回答

0

继承Collection<T>类并覆盖适当的方法,如RemoveItemClearItems。 看看在GetEnumerator

更多这方面的信息可以在MSDN

发现当我想到这一点,我想另一种方法可能是更容易,尤其是当它涉及到遍历集合和跳过软删除项目: 通过继承Collection<T>创建您自己的收藏类。删除项目时,不应只设置IsDeleted标志,而应从集合中删除项目,并将其添加到集合类中定义的其他集合中。

像这样:

public class MyBusinessCollection<T> : Collection<T> where T : BusObject 
{ 
    private readonly List<T> _deletedItems = new List<T>(); 

    protected override RemoveItem(int index) 
    { 
     var item = this[index]; 

     item.Deleted = true; 

     _deletedItems.Add(item); 

     base.RemoveItem(index); 
    } 

    public IEnumerable<T> GetDeletedItems() 
    { 
     return _deletedItems; 
    } 
} 
1

你可以实现自己的ICollection这样:

内部集合,包括已删除的项目,可以使用InternalCollection财产,如果你想写入访问数据库等

提示为CopyTo方法抛出,因为它不明显在那里实现(我们是否想要复制删除物品以及?)。

class SoftDeleteCollection<T> : ICollection<T> 
    where T : class, ISoftDelete 
{ 
    public ICollection<T> InternalCollection { get; private set; } 

    public SoftDeleteCollection() 
    { 
     this.InternalCollection = new List<T>(); 
    } 

    public IEnumerator<T> GetEnumerator() 
    { 
     return this.InternalCollection.Where(i => !i.IsDeleted).GetEnumerator(); 
    } 

    IEnumerator IEnumerable.GetEnumerator() 
    { 
     return this.GetEnumerator(); 
    } 

    public void Add(T item) 
    { 
     this.InternalCollection.Add(item); 
    } 

    public void Clear() 
    { 
     foreach (T item in this.InternalCollection.Where(item => !item.IsDeleted)) 
     { 
      item.IsDeleted = false; 
     } 
    } 

    public bool Contains(T item) 
    { 
     return this.InternalCollection.Any(i => i == item && !i.IsDeleted); 
    } 

    public void CopyTo(T[] array, int arrayIndex) 
    { 
     throw new NotSupportedException(); 
    } 

    public bool Remove(T item) 
    { 
     if (this.Contains(item)) 
     { 
      item.IsDeleted = true; 
      return true; 
     } 
     return false; 
    } 

    public int Count 
    { 
     get { return this.InternalCollection.Count(item => !item.IsDeleted); } 
    } 

    public bool IsReadOnly 
    { 
     get { return false; } 
    } 
}