【发布时间】:2020-02-19 12:43:16
【问题描述】:
我有一个名为Myitem 的类和一个派生的List 类MyItemCollection...
public class MyItemCollection : List<MyItem> { ... }
public class MyItem { ... }
我想使用 FindAll 返回包含 MyItem 值子集的 MyItemCollection 类的新实例...
public MyItemCollection GetInUse()
{
return this.FindAll(x => x.InUse);
}
但是,由于FindAll 返回List<MyItem> 而不是MyItemCollection,上述失败。
是否可以让.FindAll返回MyItemsCollection对象,或者使用.FindAll的返回来启动MyItemsCollection对象?
我可以执行以下操作,但我想知道是否有更好的解决方案...
public MyItemCollection GetInUse(bool inUse)
{
var col = new MyItemsCollection();
foreach (var item in this.FindAll(x => x.InUse))
col.Add(item);
return col;
}
【问题讨论】:
-
添加带有
IEnumerable参数的构造函数。 -
你几乎从不想要从
List<T>派生,因为你也会暴露整个列表接口(添加、删除、基于索引的访问......)。而只是使用它,例如作为实例字段。 -
@Sinatr - 是的,我确实考虑过这一点,但是我仍然需要在构造函数中有一个
foreach循环......所以看起来几乎毫无意义 -
@freefaller 不,
List<T>已经有一个“复制构造函数”,所以只需使用它,例如public MyItemCollection(IEnumerable<MyItem> collection) : base(collection) { // do whatever else you need to.. } -
@freefaller 我也会听从 HimBromBeere 的建议;
List<T>;通过组合更好地使用,因为实现List<T>为消费者提供了很多的行为。如果您追求 LINQ 行为,您始终可以实现IEnumerable<T>。
标签: c# lambda generic-list