读取c#中嵌套类的元素
本文关键字:元素 嵌套 读取 | 更新日期: 2023-09-27 18:15:31
我必须遍历类的所有成员并在Tree中显示它们。现在可以忽略Tree-Handling,在这一点上,我只需要在一个简单的列表中获得所有类成员就可以了。
我能找到的所有例子(例如递归获取属性&类的子属性)只返回以下类cTest
的前两个成员:
public class cTest
{
public String str1;
public int intwert1;
public cParent Parent = new cParent();
}
public class cParent
{
public String parentStr1;
}
没有找到public cParent Parent
字段,也没有递归处理。对于下面的代码,我已经可以看出:
Type t = typeof(cTest);
PropertyInfo[] propertyInfos;
MemberInfo[] propertyMembers;
propertyInfos = t.GetProperties();
propertyMembers = t.GetMembers();
…propertyInfos
不包含public cParent Parent
,但propertyMembers
包含public cParent Parent
!
编辑
谢谢,但还是卡住了。下面的代码为所有类成员
提供相同的信息 foreach (FieldInfo p in t.GetFields())
{
Console.WriteLine("-");
Console.WriteLine(p.GetType().ToString());
Console.WriteLine(p.Name.ToString());
Console.WriteLine(p.MemberType.GetType().ToString());
Console.WriteLine(p.MemberType.GetTypeCode().ToString());
Console.WriteLine(p.MemberType.ToString());
}
输出:^
System.Reflection.RtFieldInfo
str1
System.Reflection.MemberTypes
Int32
Field
-
System.Reflection.RtFieldInfo
int1
System.Reflection.MemberTypes
Int32
Field
-
System.Reflection.RtFieldInfo
Parent
System.Reflection.MemberTypes
Int32
Field
GetProperties()返回一个类的属性。Parent不是属性,而是字段。GetMembers()返回所有成员(属性、字段、方法等),这就是它出现在propertyMembers中的原因。使用GetFields()代替GetProperties()。
在回答附加问题时编辑:
你发布的代码是正确的给每个字段的名称。它为每个字段返回System.Reflection.MemberTypes和Int32的事实是因为您没有对字段的类型调用GetType()和GetTypeCode()。你在球场上叫他们。MemberType属性,它是System.Reflection.MemberTypes类型的枚举(它是一个Int32 enum),因此对于所有字段都是相同的。
您需要在p.p fieldtype属性上调用这些方法,该属性返回字段的类型。p. membertype属性上没有,它返回成员是方法、字段还是属性等。
所以你的代码应该是这样的:foreach (FieldInfo p in t.GetFields())
{
Console.WriteLine("-");
Console.WriteLine(p.GetType().ToString());
Console.WriteLine(p.Name.ToString());
Console.WriteLine(p.FieldType.GetType().ToString());
Console.WriteLine(p.FieldType.GetTypeCode().ToString());
Console.WriteLine(p.FieldType.ToString());
}