c# - Generic type conversion in generic method -
i have following classes (some of them in prism framework , cannot changed):
public abstract class networkeventbase<t> : compositepresentationevent<t> t : networkeventpayload { } public class networkeventpayload { } public class testevent : networkeventbase<testpayload> { } public class testpayload : networkeventpayload { } // following classes prism classes: public class compositepresentationevent<tpayload> : eventbase { } public abstract class eventbase { }
now need convert instance of testevent base class networkeventbase inside decorator ieventaggregator. ieventaggregator looks like:
public interface ieventaggregator { teventtype getevent<teventtype>() teventtype : eventbase, new(); }
now in decorator try convert this:
public class messagebusadapterinjectordecorator : ieventaggregator { ... public teventtype getevent<teventtype>() teventtype : eventbase, new() { var aggregatedevent = this.eventaggregator.getevent<teventtype>(); var networkevent = aggregatedevent networkeventbase<networkeventpayload>; if (networkevent != null) { networkevent.messagebusadapter = this.messagebusadapter; } return aggregatedevent; } }
however, networkevent null, when runtime type of aggregatedevent testevent.
you seem hope class called networkeventbase<t>
covariant in t
. generic classes can't covariant in c# (generic interfaces can).
see other threads on issue.
Comments
Post a Comment