当该属性是另一个类的数组时,获取属性的名称和值?

时间:2018-05-07 20:26:26

标签: c# system.reflection

我理解如何使用Reflection来获取给定类的属性名称和值。但是,如果该属性是包含一个或多个另一个类的数组呢?

var person = new
{
    Name = "John",
    Characteristic = new[]
    {
        new Characteristic {Name = "Age", Value = "31"},
        new Characteristic {Name = "Height", Value = "6'1""},
    }
};

var properties = person.GetType().GetProperties();
foreach (var property in properties)
{
    Console.WriteLine(property.Name);
    Console.WriteLine(property.GetValue(person));
    if (property.PropertyType.IsArray)
    {
        // Need to get info here! (See below)
    }
}

基本上,我需要得到特定属性是Characteristic的数组,然后是属性NameValue,然后是这些属性的后续值。非常感谢!

**编辑:这是我尝试的,我无法获得我需要的值...此代码代替上面的评论

foreach (var prop in property.GetType().GetProperties())
{
    Console.WriteLine(prop.Name);
    Console.WriteLine(prop.GetValue(property));
}

3 个答案:

答案 0 :(得分:0)

您仍然使用pizza is in the menu = True soup is in the menu = False dessert is in the menu = True beer is in the menue = True Type an item to see if it is in the menu: beer beer is in the menu = False 但是对于数组属性,它会返回一个强制转换为GetValue()的数组,因此您需要将其强制转换回object

Array

如果您还需要访问if (property.PropertyType.IsArray) { foreach (var item in (Array)property.GetValue(person)) Console.WriteLine(item); } 的属性,请对item个对象重复相同的属性诈骗例程:

item

更通用的版本处理任意级别的嵌套数组属性:

if (property.PropertyType.IsArray)
{
    foreach (var item in (Array)property.GetValue(person))
    {
        var subProperties = item.GetType().GetProperties();
        foreach (var subProperty in subProperties)
        {
            Console.WriteLine(subProperty.Name);
            Console.WriteLine(subProperty.GetValue(item));
        }
    }
}

N.B。在对象树中引用循环的情况下,此函数容易发生无限递归。

答案 1 :(得分:0)

检索数组实例后(正常使用GetValue),您可以使用LINQ的Cast()方法将其转换为适当类型的IEnumerable,如这样:

var characteristics = person.GetType().GetProperty("Characteristic", BindingFlags.Instance | BindingFlags.Public).GetValue(person, null) as System.Array;
foreach (var c in characteristics.Cast<Characteristic>())
{
    Console.WriteLine("{0} = {1}", c.Name, c.Value);
}

如果您没有早期访问Characteristic课程,您也可以使用纯反思:

var characteristics = person.GetType().GetProperty("Characteristic", BindingFlags.Instance | BindingFlags.Public).GetValue(person, null) as System.Array;
foreach (var o in characteristics)
{
    var name = o.GetType().GetProperty("Name", BindingFlags.Public | BindingFlags.Instance).GetValue(o, null);
    var val  = o.GetType().GetProperty("Value", BindingFlags.Public | BindingFlags.Instance).GetValue(o, null);
    Console.WriteLine("{0} = {1}", name, val);
}

两种情况下的输出是:

Age = 31
Height = 6'1"

Link to DotNetFiddle demo

答案 2 :(得分:0)

这就是我想出来的作品。这可能在上面的if语句中:

if (property.PropertyType.IsArray)
{
    foreach (var item in (Array) property.GetValue(person))
    {
        var props = item.GetType().GetProperties();
        foreach (var prop in props)
        {
            Console.WriteLine(prop.Name);
            Console.WriteLine(prop.GetValue(item));
        }
    }
}