【问题标题】:How to return an implementation of an interface with interface as return type?如何以接口作为返回类型返回接口的实现?
【发布时间】:2011-01-25 21:57:54
【问题描述】:

我有一个接口: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();}

我知道一种解决方案可能是返回基类“搜索”而不是接口的实现,但我不希望这样做,并理解为什么我不能遵循以前的模式。

任何帮助,将不胜感激。我正在努力大大简化正在发生的事情,所以如果需要任何澄清,请告诉我!

提前致谢。

【问题讨论】:

  • SearchResultSearchResultSummary之间有什么关系(如果有的话)?
  • @Jacob - 抱歉,正在缩短名称,显然错过了取出我已在帖子中修复的“摘要”
  • 这样更好。我假设FileSearchResult 也派生自SearchResult?

标签: c# generics inheritance interface


【解决方案1】:

尝试像这样声明你的界面:

interface ISearch<out T> { 
  // ...
}

(假设FileSearchResult继承自SearchResult,并且类型参数只出现在接口的协变位置)

或者,如果您总是使用SearchResults 的孩子:

interface ISearch<out T> where T : SearchResult { 
  // ...
}

更新

现在我知道您在输入位置也使用类型参数,您可以使用基本的非泛型接口:

interface ISearch { }
interface ISearch<T> : ISearch where T : SearchResult { }

// ...

public ISearch getSearchObject() { 
  return new FileSearch(); 
} 

或者segregate your interfaces (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(); 
} 

【讨论】:

  • @jordao - 我不确定“输出”给了我什么,但我正在使用 T 设置访问器的类型,当我使用 '出'
  • @jordao - 实际上,我已经这样做了,where T : SearchResult,只是认为这可能是无关信息
  • @Brett: 啊,那是个问题.... out 只能在类型参数仅用于输出(协变)位置时使用。
  • @Brett:原因是您不能将FileSearch(即ISearch&lt;FileSearchResult&gt;)转换为ISearch&lt;SearchResult&gt;。 IE。没有协方差,ISearch&lt;FileSearchResult&gt; 不是 ISearch&lt;SearchResult&gt;
猜你喜欢
  • 1970-01-01
  • 2011-05-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-22
  • 2012-10-06
  • 1970-01-01
相关资源
最近更新 更多