[英]possible to constrain output in generic method?
我有一個接口,該接口定義了對數據的各種過濾(來自EF4的查詢)。
接口方式:
IQueryable<T> filter<T>() where T : class;
現在,在該接口的具體實現中,我希望能夠做到:
public IQueryable<T> filter<T>() {
if (...) return query.OfType<Foo>().Take(100);
if (...) return query.OfType<Bar>().Blah();
// etc
}
但是當然不行,因為函數簽名期望T
而不是Foo
或Bar
。 是否有一些簡單的方法來轉換此輸出,還是需要放棄通用方法?
假設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
}
但是,您需要確保可以將它們都強制轉換為T
,否則顯然您將獲得InvalidCastExceptions。 因此,通過按照以下方式將聲明更改為someting,可以確保將T
強制轉換為任何一種類型:
public IQueryable<T> filter<T>() where T : IFooBar
其中IFooBar
是Foo
和Bar
的基類/接口
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.