[英]Get all properties of a class recursively C#
我有一堂课,看起来像
public class Employee
{
public string FirstName { get; set; };
public string LastName { get; set; };
public Address Address { get; set; };
}
public class Address
{
public string HouseNo { get; set; };
public string StreetNo { get; set; };
public SomeClass someclass { get; set; };
}
public class SomeClass
{
public string A{ get; set; };
public string B{ get; set; };
}
我想出了一种使用反射来查找类的原始属性的方法,例如字符串,int bool等
但是我还需要找出像ex这样的类中所有复杂类型的列表。 带有Class Employee的Address类和Address内的SomeClass类
如果您已经知道如何使用反射,则应该很容易:
private List<Type> alreadyVisitedTypes = new List<Type>(); // to avoid infinite recursion
public static void PrintAllTypes(Type currentType, string prefix)
{
if (alreadyVisitedTypes.Contains(currentType)) return;
alreadyVisitedTypes.Add(currentType);
foreach (PropertyInfo pi in currentType.GetProperties())
{
Console.WriteLine($"{prefix} {pi.PropertyType.Name} {pi.Name}");
if (!pi.PropertyType.IsPrimitive) PrintAllTypes(pi.PropertyType, prefix + " ");
}
}
像这样的电话
PrintAllTypes(typeof(Employee), string.Empty);
会导致:
String FirstName
Char Chars
Int32 Length
String LastName
Address Address
String HouseNo
String StreetNo
SomeClass someclass
String A
String B
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.