[英]How to return an implementation of an interface with interface as return type?
我有一個接口: ISearch<T>
,我有一個實現此接口的類: FileSearch : ISearch<FileSearchResult>
我有一個類FileSearchArgs : SearchArgs
,它有一個返回搜索對象的方法:
public override ISearch<SearchResult> getSearchObject ()
{
return ((ISearch<SearchResult>)new FileSearch());
}
這被覆蓋:
public virtual ISearch<SearchResult> getSearchObject () { return null; }
代碼只會在我向(ISearch)提供強制轉換的情況下構建,但它會在運行時拋出異常而無法轉換錯誤。 另外,前一次迭代沒有將泛型應用於接口,因此getSearchObject()
的方法簽名如下:
public override ISearch getSearchObject() { return new FileSearch();}
我知道一個解決方案可能是返回基類“搜索”而不是接口的實現,但我不想這樣做,並理解為什么我不能遵循我以前的模式。
任何幫助將不勝感激。 我正在努力大大簡化發生的事情,所以如果需要澄清,請告訴我!
提前致謝。
嘗試聲明你這樣的界面:
interface ISearch<out T> {
// ...
}
(假設FileSearchResult
繼承自SearchResult
,並且type參數僅出現在接口的協變位置)
或者如果你總是使用SearchResult
的'孩子:
interface ISearch<out T> where T : SearchResult {
// ...
}
更新 :
現在我知道你也在輸入位置使用了type參數,你可以使用一個基本的非泛型接口:
interface ISearch { }
interface ISearch<T> : ISearch where T : SearchResult { }
// ...
public ISearch getSearchObject() {
return new FileSearch();
}
或者隔離你的界面(pdf) (如果這對你有用):
interface ISearchCo<out T> where T : SearchResult {
T Result { get; }
}
interface ISearchContra<in T> where T : SearchResult {
T Result { set; }
}
// ...
public ISearchCo<SearchResult> getSearchObject() {
return (ISearchCo<SearchResult>)new FileSearch();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.