Get all properties of a class recursively C#

混江龙づ霸主 提交于 2021-01-29 07:57:19

问题


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

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


回答1:


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


来源:https://stackoverflow.com/questions/42096464/get-all-properties-of-a-class-recursively-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!