OK.
I have a class MyClass an开发者_StackOverflow社区d another class that is based on List. Let's call it MyCollection.
Now when someone types:
MyCollection coll = new MyCollection();
...
coll.Find(...)
They are acting on the entire collection. I want to apply some filtering - behind the scenes - so that if they write the above code, what actually executes is something like...
coll.Where(x=>x.CanSeeThis).Find(...)
What do I need to write in the definition of the MyCollection class to make this work?
Can I make this work?
You probably want to write a wrapper class that implements IList
or ICollection
, using a regular List
internally. This wrapper class would then proxy all method calls to the internal list, applying the filter as required.
You´ve already mentioned you´ve got your own collection, probably derived from List right? Then you´ll need to create your own method for finding:
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);
}
}
This unfortunatly is needed because you cannot override the Find method on List directly. You can however use the 'new' keyword to specify that If you´ve got a reference to the instance of MyList it will use that implementation of find, like below:
public new IEnumerable<T> Find(Predicate<T> match)
{
return this.Where(x => x.CanSeeThis).ToList().Find(match);
}
However the above example will yield:
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!
So it´s better you make you´re own method.
精彩评论