c# - How do I instantiate this 'class with generic parameter' in run-time -


this question has answer here:

consider following line of code :

classa<classb> c; 

i want create instance of c during run-time using system.reflection instead. need know type of classa , classb during run-time.

i know how type of classb

type classbtype = assemblycontaingclassb.gettype("namespace.classb"); 

q1> how can use classbtype type of classa ?

q2> understand create instance in run-time, call following line of code:

object c = activator.createinstance(typename); 

to create instance of c, typename should above code use? type of classa sufficient create instance

thanks in advance , apology if question basic. new c#.

edit:

the problem fixed. p.s.w.g's answer, there problem in getting type of class generic parameter. solution on how type of generic parameter can found here. after did p.s.w.g's answer suggest , work.

given latest update seems issue loading type classa<> @ run-time. avoid naming conflicts c# compiler generates name simpleclassname`n n number of generic type parameters, classa<> type through reflection, use name namespace.classa`1. after that, use makegenerictype method:

var classatype = assemblycontaingclassa.gettype("namespace.classa`1"); var classbtype = assemblycontaingclassb.gettype("namespace.classb"); var generictype = classatype.makegenerictype(classbtype);  object instance = activator.createinstance(generictype); 

of course, unless have load types @ run-time, it's easier , safer types @ compile-time using typeof operator:

var classatype = typeof(classa<>); var classbtype = typeof(classb); var generictype = classatype.makegenerictype(classbtype);  object instance = activator.createinstance(generictype); 

Comments

Popular posts from this blog

javascript - Count length of each class -

What design pattern is this code in Javascript? -

hadoop - Restrict secondarynamenode to be installed and run on any other node in the cluster -