将自动和隐藏过滤应用于List <t> </t>

时间:2011-01-25 11:47:15

标签: c# list lambda generic-list

行。

我有一个MyClass类和另一个基于List的类。我们称之为MyCollection。

现在有人打字:

MyCollection coll = new MyCollection();
...
coll.Find(...)

他们正在整个集合上行事。我想在幕后应用一些过滤 - 这样如果他们编写上面的代码,实际上执行的是...... ...

coll.Where(x=>x.CanSeeThis).Find(...)

我需要在MyCollection类的定义中编写什么才能使其工作?

我可以做这个吗?

2 个答案:

答案 0 :(得分:3)

您可能希望编写一个实现IListICollection的包装类,在内部使用常规List。然后,此包装类将代理对内部列表的所有方法调用,并根据需要应用过滤器。

答案 1 :(得分:1)

您已经提到过自己拥有自己的收藏品,可能来自List吧? 然后,您需要创建自己的查找方法:

public class MyList<T> : System.Collections.Generic.List<T>
{
  public IEnumerable<T> MyFind(Predicate<T> match)
  {
    return this.Where(x => x.CanSeeThis).ToList().Find(match);
  }
}

这是不幸的,因为你无法直接覆盖List上的Find方法。但是,你可以使用'new'关键字来指定如果你有一个对MyList实例的引用,它将使用find的实现,如下所示:

  public new IEnumerable<T> Find(Predicate<T> match)
  {
    return this.Where(x => x.CanSeeThis).ToList().Find(match);
  }

但是上面的例子将会产生:

MyCollection<int> collection = new ...
collection.Find(myPredicate); // <= Will use YOUR Find-method

List<int> baseTypeCollection = collection; // The above instantiated
baseTypeCollection.Find(myPredicate); // Will use List<T>.Find!

所以你最好自己制作方法。