获取嵌套属性值

时间:2015-04-17 22:41:48

标签: c#

我有一个有25个属性的类。其中一些属性是自定义对象列表。

e.g。类X3对象中的A属性是List<>个对象的B

class A 
{
    public int X1 { get; set; }

    public string X2 { get; set; }

    public List<B> X3 { get; set; }
}

B类也有公共属性:

class B
{
    public int Y1 { get; set; }

    public int Y2 { get; set; }
}

迭代类A对象属性的最佳方法是什么,以获取属性的非空值和列表中任何嵌套对象的属性?

1 个答案:

答案 0 :(得分:0)

您可以使用.NET的内置反射API迭代类型的属性。快速而肮脏的例子:

public static void Main(string[] args)
{
  var a = new A()
  {
    X1 = 1,
    X2 = "2",
    X3 = new List<B> { new B { Y1 = 5, Y2 = 7 } }
  };

  PrintProperties(a);
}

private static void PrintProperties(object obj)
{
  foreach (var prop in obj.GetType().GetProperties())
  {
    var propertyType = prop.PropertyType;
    var value = prop.GetValue(obj);

    Console.WriteLine("{0} = {1} [{2}]", prop.Name, value, propertyType);

    if (typeof(IList).IsAssignableFrom(propertyType))
    {
      var list = (IList)value;

      foreach (var entry in list)
      {
        PrintProperties(entry);
      }
    }
    else
    {
      if (prop.PropertyType.Namespace != "System")
      {
        PrintProperties(value);
      }
    }
  }
}

正如您已经被告知的那样,当您的类型在编译时已知时,不应使用此类代码。

相关问题