gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 13:21:22 26 4
gpt4 key购买 nike

在 .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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com