Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# GetValue of PropertyInfo with SubClasses

First of all, sorry for my bad English... I hope you'll understand what I want to say.

I have a problem with a little code where I need to get the value of class' properties. (That's not my full project, but the concept of what I want to do. And with this simple code, I'm blocked.)

There is the code: (This sample works correctly.)

using System;
using System.Reflection;

class Example
{
    public static void Main()
    {
        test Group = new test();
        BindingFlags bindingFlags = BindingFlags.Public |
                                    BindingFlags.NonPublic |
                                    BindingFlags.Instance |
                                    BindingFlags.Static;
        Group.sub.a = "allo";
        Group.sub.b = "lol";

        foreach (PropertyInfo property in Group.GetType().GetField("sub").FieldType.GetProperties(bindingFlags))
        {
            string strName = property.Name;
            Console.WriteLine(strName + " = " + property.GetValue(Group.sub, null).ToString());
            Console.WriteLine("---------------");
        }
    }
}

public class test
{
    public test2 sub = new test2();
}

public class test2
{
    public string a { get; set; }
    public string b { get; set; }
}

But I want to replace Group.sub with a dynamic accessing (like the foreach with GetField(Var) where it works). I tried a lot of combinations, but I haven't found any solutions.

property.GetValue(property.DeclaringType, null)

or

property.GetValue(Group.GetType().GetField("sub"), null)

or

property.GetValue(Group.GetType().GetField("sub").FieldType, null)

So I think you understand. I would like to give the instance of object Group.sub dynamically. Because, on my full project, I have a lot of subclasses.

Any ideas?

like image 537
Kevin Joss Avatar asked Oct 17 '22 19:10

Kevin Joss


1 Answers

You're already accessing the sub field using Group.GetType().GetField("sub"), you'll need to get its value and hold on to it:

FieldInfo subField = Group.GetType().GetField("sub");

// get the value of the "sub" field of the current group
object subValue = subField.GetValue(Group);
foreach (PropertyInfo property in subField.FieldType.GetProperties(bindingFlags))
{
    string strName = property.Name;
    Console.WriteLine(strName + " = " + property.GetValue(subValue, null).ToString());    
}
like image 88
C.Evenhuis Avatar answered Nov 15 '22 05:11

C.Evenhuis