[英]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.