.NET,C#,Reflection:列出字段的字段,字段本身具有字段

Jay*_*Fix 3 .net c# reflection recursion

在.NET&C#中,假设ClassB有一个类型的字段ClassA.人们可以很容易地使用方法GetFields来列出ClassB字段.不过,我想列出这些领域的ClassB那场本身具有的字段.例如,ClassB你的能量场x有田b,si.我想(以编程方式)列出这些字段(正如我在以下代码中的评论所建议的那样).

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 ( )
        {
        ClassA myAObject = new ClassA () ;
        ClassB myBObject = new ClassB () ;

        //  My goal is this:
        //    ***Using myBObject only***, print its fields, and the fields
        //    of those fields that, *themselves*, have fields.
        //  The output should look like this:
        //    Int64   l
        //    ClassA  x
        //               Byte   b
        //               Int16  s
        //               Int32  i

        }
    }
Run Code Online (Sandbox Code Playgroud)

Mar*_*age 7

使用它FieldInfo.FieldType来反映类中字段的类型.例如

fieldInfo.FieldType.GetFields();
Run Code Online (Sandbox Code Playgroud)

以下是基于您的代码的完整示例,如果您有ClassZ内部代码,则使用递归ClassA.如果你有一个循环对象图,它会中断.

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);
    }
  }

}
Run Code Online (Sandbox Code Playgroud)


Ton*_*pel 6

执行此操作的类已经存在!看一下Visual Studio的Microsoft C#示例:http://code.msdn.microsoft.com/Release/ProjectReleases.aspx?ProjectName = csharpsamples&ReleaseId = 8

具体来说,看看ObjectDumper示例,因为它深入n级.例如:

ClassB myBObject = new ClassB();
...
ObjectDumper.Write(myBObject, Int32.MaxValue); 
//Default 3rd argument value is Console.Out, but you can use 
//any TextWriter as the optional third argument
Run Code Online (Sandbox Code Playgroud)

它已经考虑了图表中的对象是否已被访问,值类型与对象类型与可枚举类型等.