c# - .NET,C#,反射 : list the fields of a field that, 本身,有字段

标签 c# .net reflection recursion

在 .NET 和 C# 中,假设 ClassB 有一个类型为 ClassA 的字段。 可以很容易地使用方法 GetFields 列出 ClassB 的字段。 但是,我想列出它们自己 具有字段的那些ClassB 字段的字段。 例如,ClassB 的字段x 有字段bsi。我想(以编程方式)列出这些字段(正如我在下面代码中的评论所建议的那样)。

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

        }
    }

最佳答案

使用 FieldInfo.FieldType 反射(reflect)类中字段的类型。例如

fieldInfo.FieldType.GetFields();

这是一个基于您的代码的完整示例,如果您在 ClassA 中有 ClassZ,则使用递归。如果您有循环对象图,它就会中断。

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

}

关于c# - .NET,C#,反射 : list the fields of a field that, 本身,有字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1120839/

相关文章:

c# - 多次插入需要设置 Id 属性吗?

c# - 评论存储在哪里以及如何提取它们?

c# - 将 Func<T> 重构为 Expression<Func<T>>

java - 在重写方法上使用 Method.getReturnType()

c# - XDocument.Descendants(itemName) - 查找合格名称时出现问题

c# - 如何使用 LINQ 查询包含多个子表?

c# - Windows 窗体 : Making a cursor bitmap partially transparent

.net - 当 url 在浏览器中工作时添加服务引用给我错误

java - 如何确定字段在哪个类中声明

c# - 我可以不加思索地做到这一点吗?