c# - How to trigger a Generic Class method recursively changing the type of T? -
c# - How to trigger a Generic Class method recursively changing the type of T? -
i've created generic class parse info instance of class (myclass1
). since myclass1
has built-in c# types, genericmethod
works fine. problem starts grow when myclass1
has myclass2
property , still want invoke genericmethod
parse data.
i can't trigger generic class method within scope since need alter type of t
. there way solve problem?
public class myclass1 { public int myintproperty { get; set; } public string mystringproperty { get; set; } public myclass2 myclass2property { get; set; } } public class myclass2 { public int myotherintproperty { get; set; } public string myotherstringproperty { get; set; } public bool myotherboolproperty { get; set; } } public class mygenericclass<t> t : class { public static t mygenericmethod() { t o = (t)activator.createinstance(typeof(t)); propertyinfo[] pi = typeof(t).getproperties(); for(int = 0; < pi.count(); i++) { if(pi[i].name == "myclass2property") { //how proceed ? mygenericclass<???>.mygenericmethod(); } else { pi[i].setvalue(o, convert.changetype(somevalue, pi[i].propertytype), null); } } } } public static void main(string[] args) { myclass1 mc1 = mygenericclass<myclass1>.mygenericmethod(); //do mc1 }
you can @ this post
and maybe seek this
public static class mygenericclass<t> t : class { public static t mygenericmethod() { t o = (t)activator.createinstance(typeof(t)); propertyinfo[] pi = typeof(t).getproperties(); for(int = 0; < pi.count(); i++) { if(pi[i].name == "myclass2property") { //how proceed ? type t = typeof (mygenericclass<>); type generictype = t.makegenerictype(new system.type[] { pi[i].propertytype }); var c = activator.createinstance(generictype); dynamic mgm = convert.changetype(c, generictype); mgm.mygenericmethod(); } else { pi[i].setvalue(o, convert.changetype(somevalue, pi[i].propertytype), null); } } }
c# asp.net generics system.reflection
Comments
Post a Comment