mardi 20 février 2018

How to convert fieldinfo to it's actually class object? using C#

i need to create program that navigate an object structure and print the structure of any “struct” provided as an argument.

These "structs" are defined as follows:

  • They have only public attributes
  • Each attribute can be of the following types:
    • “Structs”
    • Primitive (e.g. int), primitive wrapper (e.g. Integer) or String

the problem is when i'm trying to print data member which is a class or struct. i'm trying to to write a recursive function that gets an object and check each field in the object: if it's a class them i send again the curr field to the same function. else i print the value of the field.

this is my code. but when i send the fieldInfo to the function the code line: ---> Type objType = i_obj.GetType();

is getting me the next value: object.GetType returned {Name = "RtFieldInfo" FullName = System.Reflection.RtFieldInfo"} System.RuntimeType

    public static void getObj(object i_obj)
    {
        Type objType = i_obj.GetType();

        FieldInfo[] objField = objType.GetFields();

        foreach (FieldInfo member in objField)
        {
            Type memberType = member.FieldType;

            if(memberType.IsClass)
            {                    
                getObj(member);
            }

            else
            {
                Console.WriteLine(member.Name + " : " + member.GetValue(i_obj));
            }

        }
    }

how can i get the real object from fieldInfo ??





Aucun commentaire:

Enregistrer un commentaire