通用列表中的C#Cast对象

时间:2019-03-15 17:07:18

标签: c# reflection casting generic-list typeof

我有一个带有属性的对象。一些属性是通用列表。例如IList<IArticle>IList<IProduct>,依此类推。

我使用myObject.GetType().GetProperties()遍历对象中的所有属性,并搜索IList类型的属性。

我可以识别IList属性,并希望遍历列表。但是我有问题。我不能将listProperty(属于object类型)转换为通用列表。问题在于属性是不同的泛型类型。强制转换为IList仅适用于类型为IList<IArticle>的属性,而不适用于其他类型的IList<IProdukt> ...

投射到IList<object>始终为空。

这是示例代码:

foreach (var myProperty in myObject.GetType().GetProperties())
{
    //get generic property (type IList)
    if (myProperty.PropertyType.IsGenericType)
    {
        PropertyInfo propInfo = myObject.GetType().GetProperty(myProperty.Name);
        Type propType = myObject.GetType().GetProperty(myProperty.Name).PropertyType;
        var listProperty = propInfo.GetValue(myProperty);

        foreach (var test in (listProperty as IList<???>))
        {
            //Do some magic
        }
    }
}

1 个答案:

答案 0 :(得分:0)

这是遍历列表的解决方案。只需强制转换为IEnumerable。 不要忘记包含using System.Collections;

foreach (var myProperty in myObject.GetType().GetProperties())
{
    //get generic property (type IList)
    if (myProperty.PropertyType.IsGenericType)
    {
        var listProperty = myProperty.GetValue(myObject) as IEnumerable;

        foreach (var test in listProperty)
        {
            //Do some magic
        }
    }
}
相关问题