c# 4.0 - Type parameters - get concrete type from type T : IMyInterface -


suppose have list<imyinterface>...

i have 3 classes implement imyinterface: myclass1, myclass2, , myclass3

i have readonly dictionary:

private static readonly dictionary<type, type> declarationtypes = new dictionary<type, type> {     { typeof(myclass1), typeof(funnyclass1) },     { typeof(myclass2), typeof(funnyclass2) },     { typeof(myclass3), typeof(funnyclass3) }, }; 

i have interface, ifunnyinteface<t> t : imyinterface

i have method:

public static ifunnyinterface<t> converttofunnyclass<t>(this t node) t : imyinterface {     if (declarationtypes.containskey(node.gettype())) {         ifunnyinterface<t> otherclassinstance = (funnyinterface<t>) activator.createinstance(declarationtypes[node.gettype()], node);         return otherclassinstance;     }     return null; } 

i'm trying call constructor of funnyclasses , insert parameter myclass object. don't want know object is: want instantiate funnyclass myclass parameter.

what happens when call converttofunnyclass, t of type imyinterface, , when try cast funnyinterface<t>, says can't convert funnyclass1, instance, funnyinterface<imyinterface>

my current workaround (not beautiful one), this:

public static dynamic converttofunnyclass<t>(this t node) t : imyinterface {     if (declarationtypes.containskey(node.gettype())) {         var otherclassinstance = (funnyinterface<t>) activator.createinstance(declarationtypes[node.gettype()], node);         return otherclassinstance;     }     return null; } 

and don't because return type dynamic, when access somewhere else, have no idea type is, , lose intellisense, , stuff. don't know performance implications either.

any clues?

thanks in advance!

resolution

as i'm using c# 4.0, stop casting errors using covariance (output positions only), , changed ifunnyinterface to

ifunnyinteface<out t> t : imyinterface 

thank replies.

essentially, problem trying convert funnyinterface<t> funnyinterface<imyinterface>. has been mentioned several times (one example here, more information here), not valid in circumstances. in .net 4, when generic type interface or delegate, , type parameter has been explicitly declared variant in or out, can perform conversion.

is funnyinterface interface?


Comments

Popular posts from this blog

c# - How to set Z index when using WPF DrawingContext? -

razor - Is this a bug in WebMatrix PageData? -

visual c++ - Using relative values in array sorting ( asm ) -