如何在C#中递归地从嵌套类中检索成员字段
本文关键字:嵌套 检索 字段 成员 递归 | 更新日期: 2023-09-27 18:19:35
我正在调用一个方法GetEmployee()
,该方法返回类型为Employee
的值并存储在emp
变量中。
var emp = GetEmployee();
我需要检索Employee类的所有成员字段,如年龄、姓名,以及嵌套类(如)的成员
[Address->DoorNum,Street,Zip]
[Phone->mobile,homePhone],
[Dependents->name,age,
[phone->mobile,homePhone]]
从CCD_ 4变量递归地生成。
类结构如下:
class Employee
{
int age;
string name
Address address;
Phone[] phones;
Dependents[] dependents;
}
class Address
{
int DoorNum;
string Street;
int Zip;
}
class Phone
{
string mobile;
string homePhone;
}
class Dependents
{
string name;
int age;
Phone depPhone;
}
你能帮我怎样才能做到这一点吗?
如果您谈论的是在运行时动态检索字段,这里有一个简单的递归示例,旨在说明而非实用性。请注意,默认情况下,类字段被推断为私有字段。
public static void listFields(Type type, bool sameNamespace, int nestLevel = 1) {
BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;
Console.WriteLine("'r'n{0}Fields of {1}:", tabs(nestLevel - 1), type.Name);
foreach (FieldInfo f in type.GetFields(bf)) {
Console.WriteLine("{0}{1} {2} {3}", tabs(nestLevel), (f.IsPublic ? "public" : "private"), f.FieldType.Name, f.Name);
Type fieldType = (f.FieldType.IsArray) ? f.FieldType.GetElementType() : f.FieldType;
if ((type != fieldType) && (!sameNamespace || fieldType.Namespace == type.Namespace)) {
listFields(fieldType, sameNamespace, nestLevel + 2);
}
}
Console.WriteLine();
}
private static String tabs(int count) { return new String(' ', count * 3); }
listFields(typeof(Employee), true);
:输出
Fields of Employee:
private Int32 age
private String name
private Address address
Fields of Address:
private Int32 DoorNum
private String Street
private Int32 Zip
private Phone[] phones
Fields of Phone:
private String mobile
private String homePhone
private Dependents[] dependents
Fields of Dependents:
private String name
private Int32 age
private Phone depPhone
Fields of Phone:
private String mobile
private String homePhone
如果您想实际获得实例的字段值,可以使用FieldInfo.GetValue(object)
我终于得到了问题的答案:
public Employee getEmployee()
{
var emp=EmployeeProxy.GetEmployee();
return new Employee {
name=emp.Name,
age=emp.Age,
address=emp.AddressType.Select(a=>new Address{
DoorNum=a.doorNum,
Street=ae.street,
Zip=a.zip,
}),
phones=new Phone[]{
mobile=PhoneType.Mobile,
homePhone=PhoneType.HomePhone,
},
dependents=emp.DependentsType.Select(d=>new Dependents{
name=d.Name,
age=d.Age,
depPhone=new Phone{
mobile=d.DependentPhone.Mobile,
homePhone=d.DependentPhone.HomePhone,
},
}),
}; //End of Return
} //End of method