递归获取类的所有属性 C# [英] Get all properties of a class recursively C#
本文介绍了递归获取类的所有属性 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 等
I have figured out a way finding out Properties in a class which are primitive like the string, int bool etc using Reflection
但我还需要找出一个类中所有复杂类型的列表,例如 for ex.类 Address 与类 Employee 和类 SomeClass 内的 Address
But I also need to find out the list of all complex types in a class like for ex. class Address withing Class Employee and class SomeClass within Address
推荐答案
如果您已经知道如何使用反射,这应该很容易:
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 + " ");
}
}
还有这样的电话
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
这篇关于递归获取类的所有属性 C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文