[英]possible to constrain output in generic method?
I have an interface which defines various filtering on data (queries coming from EF4). 我有一个接口,该接口定义了对数据的各种过滤(来自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
. 但是当然不行,因为函数签名期望T
而不是Foo
或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: 假设Foo
和Bar
类都可以被强制转换为T
,则可以这样工作:
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. 但是,您需要确保可以将它们都强制转换为T
,否则显然您将获得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: 因此,通过按照以下方式将声明更改为someting,可以确保将T
强制转换为任何一种类型:
public IQueryable<T> filter<T>() where T : IFooBar
Where IFooBar
is the base class/interface for both Foo
and Bar
其中IFooBar
是Foo
和Bar
的基类/接口
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.