.NET, C#, Reflection: list the fields of a field that, itself, has fields

前端 未结 5 1793
轻奢々
轻奢々 2020-12-11 08:53

In .NET & C#, suppose ClassB has a field that is of type ClassA. One can easily use method GetFields to list ClassB\'

5条回答
  •  鱼传尺愫
    2020-12-11 09:20

    Use the FieldInfo.FieldType to reflect over the type of the fields in your class. E.g.

    fieldInfo.FieldType.GetFields();
    

    Here is a complete sample based on your code that uses recursion in case you have ClassZ inside ClassA. It breaks if you have a cyclic object graph.

    using System;
    using System.Reflection;
    
    class ClassA {
      public byte b;
      public short s; 
      public int i;
    }
    
    class ClassB {
      public long l;
      public ClassA x;
    }
    
    class MainClass {
    
      public static void Main() {
        ClassB myBObject = new ClassB();
        WriteFields(myBObject.GetType(), 0);
      }
    
      static void WriteFields(Type type, Int32 indent) {
        foreach (FieldInfo fieldInfo in type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)) {
          Console.WriteLine("{0}{1}\t{2}", new String('\t', indent), fieldInfo.FieldType.Name, fieldInfo.Name);
          if (fieldInfo.FieldType.IsClass)
            WriteFields(fieldInfo.FieldType, indent + 1);
        }
      }
    
    }
    

提交回复
热议问题