How to return an implementation of an interface with an interface as a return type?

I have an interface : ISearch<T>, and I have a class that implements this interface:FileSearch : ISearch<FileSearchResult>

I have a class FileSearchArgs : SearchArgsthat has a method to return a search object:

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

This is canceled from:

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

The code will only be built if I provided a cast to (ISearch), but it throws an exception at runtime with a transfer error. In addition, the previous iteration did not apply generalization to the interface, and therefore the method signature getSearchObject()was as follows:

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

I know that one of the solutions could be to return the base class "Search" instead of implementing the interface, but I would prefer not to do this and understand why I can not follow the pattern that I previously had.

, . , , , - , , !

.

+3
1

:

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

(, FileSearchResult SearchResult type )

, SearchResult s 'children:

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

UPDATE

, , 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(); 
} 
+3

Source: https://habr.com/ru/post/1787815/


All Articles