c# - How to cast object1<object2> to interface of object1<interface of object2>? -
lets have arrangement:
public interface icreatable { int createdbyuserid { get; set; } } public class unicorn : icreatable { public int createdbyuserid { get; set; } } public interface icrudservice<t> t : class, icreatable { t dosomething(t t); } public class unicornservice : icrudservice<unicorn> { public unicorn dosomething(unicorn unicorn) { var createdbyuserid = unicorn.createdbyuserid; // ... return unicorn; } } and use so:
static void main(string[] args) { var unicorn = new unicorn(); var unicornservice = new unicornservice(); unicornservice.dosomething(unicorn); } this runs fine. however, lets want cast unicornservice it's interface type of icrudservice along it's generic type it's interface type such:
var crudservice = unicornservice icrudservice<icreatable>; i run problems. how looks:
unicornservice icrudservice<unicorn> --> casts fine unicornservice icrudservice<icreatable> --> casts null it seems since unicorn derives icreatable , since icrudservice<t> t: class, icreatable should have no problems working out. searches started leading me covariance , contravariances i'm getting lost @ level.
how can cast crudservice icrudservice<icreatable>?
update:
using covariance such:
public interface icrudservice<out t> then makes intellisense "invalid variance: type parameter 't' must contravariantly valid on 'icrudservice.dosomething(t)'. 't' covariant." how work?
an icrudservice<unicorn> cannot treated icrudservice<icreatable>.
an icrudservice<unicorn> object allowed accept parameters of type unicorn or subtypes of unicorn, icrudservice<icreatable> can accept parameter of someothertypeoficreatable.
you unicornservice type allowed use members specific unicorn, not icreatable, since that's type restricted it's function to. restriction prohibits meeting more general interface's api.
so, in short, it's not possible.
Comments
Post a Comment