简体   繁体   English

如何将接口的实现作为返回类型返回?

[英]How to return an implementation of an interface with interface as return type?

I have an interface: ISearch<T> and I have a class which implements this interface: FileSearch : ISearch<FileSearchResult> 我有一个接口: ISearch<T> ,我有一个实现此接口的类: FileSearch : ISearch<FileSearchResult>

I have a class FileSearchArgs : SearchArgs which has a method to return the a search object: 我有一个类FileSearchArgs : SearchArgs ,它有一个返回搜索对象的方法:

public override ISearch<SearchResult> getSearchObject () 
{ 
   return ((ISearch<SearchResult>)new FileSearch()); 
}

This is overridden from: 这被覆盖:

public virtual ISearch<SearchResult> getSearchObject () { return null; }

The code would only build if I provided the cast to (ISearch), but it throws an exception at runtime with an unable to cast error. 代码只会在我向(ISearch)提供强制转换的情况下构建,但它会在运行时抛出异常而无法转换错误。 Additionally, a previous iteration did not apply generics to the interface, and thus the method signature of getSearchObject() was as follows: 另外,前一次迭代没有将泛型应用于接口,因此getSearchObject()的方法签名如下:

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

I know one solution could be to return a base class "Search" instead of an implementation of the interface, but I'd prefer not to do this, and understand why I cannot follow the pattern I previously had. 我知道一个解决方案可能是返回基类“搜索”而不是接口的实现,但我不想这样做,并理解为什么我不能遵循我以前的模式。

Any help, would be greatly appreciated. 任何帮助将不胜感激。 I'm trying to greatly simplify what is going on, so if any clarification is needed, please let me know! 我正在努力大大简化发生的事情,所以如果需要澄清,请告诉我!

Thanks in advance. 提前致谢。

Try to declare you interface like this: 尝试声明你这样的界面:

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

(assuming that FileSearchResult inherits from SearchResult , and that the type parameter only occurs in covariant positions in the interface) (假设FileSearchResult继承自SearchResult ,并且type参数仅出现在接口的协变位置)

Or if you'll always use SearchResult s' children: 或者如果你总是使用SearchResult的'孩子:

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

UPDATE : 更新

Now that I know you use the type parameter also in an input position, you could use a base non-generic interface: 现在我知道你也在输入位置使用了type参数,你可以使用一个基本的非泛型接口:

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

// ...

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

Or segregate your interfaces (pdf) (if that makes sense for you): 或者隔离你的界面(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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM