possible to constrain output in generic method?
I have an interface which defines various filtering on data (queries coming from EF4).
Interface method:
IQueryable<T> filter<T>() where T : class;
Now in a concrete implementation of that interface, I want to be able to do:
public IQueryable<T> filter<T>() {
if (...) return query.OfType<Foo>().Take(100);
if (...) return query.OfType<Bar>().Blah();
// etc
}
But of course that doesn't work as the function signature expects T
and not Foo
or Bar
. Is there some simple way to 开发者_如何学编程cast this output, or do I need to forgo the generic approach?
Assuming Foo
and Bar
classes can both be cast as T
, something like this would work:
public IQueryable<T> filter<T>() {
if (...) return query.OfType<Foo>().Take(100).Cast<T>();
if (...) return query.OfType<Bar>().Blah().Cast<T>();
// etc
}
However, you need to make sure that they can both be cast as T
, or else you'll obviously get InvalidCastExceptions. So you would be well-served to make sure T
can be cast to either type by changing your declaration to someting along the lines of:
public IQueryable<T> filter<T>() where T : IFooBar
Where IFooBar
is the base class/interface for both Foo
and Bar
精彩评论