I realise the question sounds similar to some others, but they don't really answer what I need. I'm trying to use Reflection to put a big "data" class which has other data classes within it and get all these values to quickly create a JSON so that every time a new piece of data is added there is no need to re-code anything.
So, basically it would look something like this:
public class A
{
public int data1 { set; get; }
public B b { set; get; }
}
public class B
{
public int data2 { set; get; }
}
//main method
{
A a = new A();
a.data1 = 1;
a.b = new B();
a.b.data2 = 2;
PropertyInfo[] propInfos = typeof(A).GetProperties();
foreach (PropertyInfo propInfo in propInfos)
{
// ??
//if (!propInfo.GetType().IsPrimitive)
//{
// PropertyInfo[] propInfosForB = propInfo.GetType().GetProperties();
// foreach (PropertyInfo propInfoForB in propInfos)
// {
// print(propInfoForB.GetValue(propInfo, null));
// }
//}
//else
{
print(propInfo.GetValue(a, null));
}
}
}
So basically "1" prints fine, but I can't figure out how to get "2" from B (as part of A). All I get is loads of "1" and "B" printed or errors. Hope that makes sense.
P.S: I know serialization would be a simpler solution to put all this in a JSON, but I can't use that for different reasons.
Aucun commentaire:
Enregistrer un commentaire