[英]Get all properties of a class recursively C#
I have a class which looks like 我有一堂课,看起来像
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; };
}
I have figured out a way finding out Properties in a class which are primitive like the string, int bool etc using Reflection 我想出了一种使用反射来查找类的原始属性的方法,例如字符串,int bool等
But I also need to find out the list of all complex types in a class like for ex. 但是我还需要找出像ex这样的类中所有复杂类型的列表。 class Address withing Class Employee and class SomeClass within Address
带有Class Employee的Address类和Address内的SomeClass类
If you already know how to use reflection, this should be easy: 如果您已经知道如何使用反射,则应该很容易:
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 + " ");
}
}
And a call like 像这样的电话
PrintAllTypes(typeof(Employee), string.Empty);
would result in: 会导致:
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.