c# - How to return an implementation of an interface with interface as return type? -
i have interface:isearch<t>
, have class implements interface: filesearch : isearch<filesearchresult>
i have class filesearchargs : searchargs
has method return search object:
public override isearch<searchresult> getsearchobject () { return ((isearch<searchresult>)new filesearch()); }
this overridden from:
public virtual isearch<searchresult> getsearchobject () { return null; }
the code build if provided cast (isearch), throws exception @ runtime unable cast error. additionally, previous iteration did not apply generics interface, , method signature of getsearchobject()
follows:
public override isearch getsearchobject() { return new filesearch();}
i know 1 solution return base class "search" instead of implementation of interface, i'd prefer not this, , understand why cannot follow pattern had.
any help, appreciated. i'm trying simplify going on, if clarification needed, please let me know!
thanks in advance.
try declare interface this:
interface isearch<out t> { // ... }
(assuming filesearchresult
inherits searchresult
, , type parameter occurs in covariant positions in interface)
or if you'll use searchresult
s' children:
interface isearch<out t> t : searchresult { // ... }
update:
now know use type parameter in input position, use base non-generic interface:
interface isearch { } interface isearch<t> : isearch t : searchresult { } // ... public isearch getsearchobject() { return new filesearch(); }
or segregate interfaces (pdf) (if makes sense you):
interface isearchco<out t> t : searchresult { t result { get; } } interface isearchcontra<in t> t : searchresult { t result { set; } } // ... public isearchco<searchresult> getsearchobject() { return (isearchco<searchresult>)new filesearch(); }
Comments
Post a Comment