我想创建一个业务对象集合类(List of T)。我的业务对象有一个Deleted属性(所以我可以跟踪DB的删除)。集合类需要覆盖List的remove,for-each枚举方法等,以便我可以将业务对象标记为已删除,而不是从列表中“物理”删除,并在枚举期间跳过它们。到目前为止,我有一个继承List(BusObject)的类,但是我发现一些List方法(即Remove)不能被覆盖。我接近这个错误吗?也许我不应该继承List并使用我自己的方法在内部管理列表?.NET业务对象集合(列表)
0
A
回答
0
继承Collection<T>
类并覆盖适当的方法,如RemoveItem
和ClearItems
。 看看在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; }
}
}
0
看看继承自ObservableCollection。这可能会帮助你。
级裁判:https://msdn.microsoft.com/en-us/library/ms668604(v=vs.110).aspx
八九不离十类似的线程,与它有帮助的注释:C# Custom Observable Collection - Should I use Composition or Inheritance?
相关问题
- 1. VB .Net列表框和对象集合
- 2. Powershell对象[]到.Net集合?
- 3. 业务对象和代码列表
- 4. 我能加入.NET集合中的列表对象与EF
- 5. .Net ORM /业务对象框架性能
- 6. 集团和聚合对象的列表
- 7. MVC在Json中序列化对象,对象列表,集合
- 8. 设计DAL /数据集/业务对象
- 9. 在业务对象和集合中使用泛型
- 10. 模板使用的业务对象的集合在DataGrid
- 11. 在业务对象集合属性WPF数据验证
- 12. 结合两列在业务共享的列值的对象
- 13. C#.NET和直接对象集合
- 14. 将Json转换为.NET对象集合
- 15. .NET集合和访问对象方法
- 16. 如何验证.NET集合的对象?
- 17. .NET对象从集合/枚举
- 18. ASP.NET Web服务 - 使用列表/集合传递基础对象?
- 19. 业务对象4.0 webi结合行
- 20. 业务对象 - 业务视图 - 合并数据库
- 21. 从业务层添加对象到水晶报表(c#.net)
- 22. 架构业务集合
- 23. 业务对象应该知道它对应的合同对象
- 24. 查询蒙戈DB的对象集合内对象的列表
- 25. SAP业务对象
- 26. SAP业务对象
- 27. WPF业务对象
- 28. 对象集合
- 29. 对象集合
- 30. 水晶报表数据源到业务层对象收集