【问题标题】:Get all properties of a class recursively C#递归获取类的所有属性 C#
【发布时间】:2022-03-26 18:46:18
【问题描述】:

我有一个看起来像的类

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 等使用反射的原始类

但我还需要找出类中所有复杂类型的列表,例如 for ex。类Address with Class Employee 和类SomeClass 在Address 中

【问题讨论】:

    标签: c# .net system.reflection


    【解决方案1】:

    如果你已经知道如何使用反射,这应该很容易:

    private List<Type> alreadyVisitedTypes = new List<Type>(); // to avoid infinite recursion
    public 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-24
      • 2012-03-15
      • 1970-01-01
      • 2011-10-20
      • 2011-05-12
      • 2015-08-16
      • 2011-01-24
      • 2014-02-05
      相关资源
      最近更新 更多