c# - How to upcast generic type parameters -
when use reflection in case, created type can many generic types.
basestephandler<basestepdatamodel> activator = (basestephandler<basestepdatamodel>)activator.createinstance(....); the created instance can childs of basestepdatamodel.
basestephandler<onedatamodel>
or
basestephandler<twodatamodel>
onedatamodel , twodatamodel extending basestepdatamodel.
this exception get:
unable cast object of type '....globalonboardingsteponehandler' type '....basestephandler`1[....basestepdatamodel]'.
this declaration if globalonboardingsteponehandler.
public class globalonboardingsteponehandler : basestephandler<globalonboardingsteponedatamodel>{}
you getting exception because globalonboardingsteponehandler inherits basestephandler<globalonboardingsteponedatamodel>, not basestephandler<basestepdatamodel>. common mistake .net generics. generics not covariant type parameters.
see:
c#: cast generic interface base type
http://blogs.msdn.com/b/csharpfaq/archive/2010/02/16/covariance-and-contravariance-faq.aspx
etc...
the issue you assume because globalonboardingsteponedatamodel inherits basestepdatamodel, globalonboardingsteponehandler inherits basestephandler<basestepdatamodel>. isn't case, , can't cast 1 other.
as example, consider following:
var mylistofstrings = new list<string>(); // logic, should compile (it doesn't): var mylistofobjects = ((list<object>)mylistofstrings); // if did, possible: mylistofobjects.add(1); // holy cow, added integer list of strings! world coming to? now, confusing recovering java programmers because this possible in java. in java, have type erasure, @ runtime list<string> list<object>, , can cast like, , put want it. because clr uses reified generics, not type erasure, list<string> separate , distinct type list<object> or list<integer>
Comments
Post a Comment