List in ListInfo获取属性迭代

时间:2012-12-28 10:57:38

标签: c# generics reflection

我的列表为ProductSpec {id, Name},另一个列表为Product {productspec, id, Name}。 当我尝试访问Product的属性

IList<PropertyInfo> properties = typeof(Product).GetProperties().ToList();

我正在修改我的身份和姓名作为财产,这很好,但当我试图重申productpec为

foreach(var property in properties)
{
    IList<PropertyInfo> properties = property.propertytype.getproperties();
    // I am not getting the productspec columns 
    //instead I am getting (capacity,count ) as my properties..
}

那么如何重复列表中的列表以获取列表属性

3 个答案:

答案 0 :(得分:3)

您需要为属性类型使用相同的代码:

var innerProperties = property.PropertyType.GetProperties().ToList();

同样重命名结果 - 它与foreach循环中的变量冲突。

答案 1 :(得分:3)

类型ProductSpecProduct类型的ProductSpec类中List<ProductSpec>的类型是什么?如果是列表,您可以执行以下操作:

var properties = new List<PropertyInfo>();
foreach (var property in properties)
{
    if (typeof(IEnumerable).IsAssignableFrom(property.PropertyType)
        && property.PropertyType.IsGenericType
        && property.PropertyType.GetGenericArguments().Length == 1)
    {
        IList<PropertyInfo> innerProperties = property.PropertyType.GetGenericArguments()[0].GetProperties();
        //should contain properties of elements in lists
    }
    else
    {
        IList<PropertyInfo> innerProperties = property.PropertyType.GetProperties();
        //should contain properties of elements not in a list
    }
}

答案 2 :(得分:0)

试试这个:

    PropertyInfo[] propertyInfos = typeof(Product).GetProperties();
        foreach (var propertyInfo in propertyInfos)
        {
            var inner = propertyInfo.PropertyType.GetProperties().ToList();
        }

public class Product
{
    public ProductSpec Spec { get; set; }

    public string Id { get; set; }

    public string Name { get; set; }
}

public class  ProductSpec
{
    public string Id { get; set; }

    public string Name { get; set; }
}
相关问题