简体   繁体   English

泛型列表中的 C# 投射对象

[英]C# Cast Object in generic list

I have an object with properties.我有一个带有属性的对象。 Some properties are generic list.一些属性是通用列表。 For example IList<IArticle> or IList<IProduct> and so on.例如IList<IArticle>IList<IProduct>等等。

I iterate over all properties in the object with myObject.GetType().GetProperties() and search for properties which are from type IList.我使用myObject.GetType().GetProperties()遍历对象中的所有属性并搜索来自 IList 类型的属性。

I can identify the IList-properties and would like to iterate over the list.我可以识别 IList 属性并希望遍历列表。 But there is my problem.但是有我的问题。 I can't cast the listProperty (which is of type object) into generic list.我无法将 listProperty(它是对象类型)转换为通用列表。 The problem is that the properties are different generic types.问题在于属性是不同的泛型类型。 To cast into IList will work only for the property which are from type IList<IArticle> , but not for the rest like IList<IProdukt> ...转换为 IList 仅适用于IList<IArticle>类型的IList<IArticle> ,但不适用于IList<IProdukt> ...

Cast into IList<object> is always null.转换为IList<object>始终为 null。

Here is a example code:这是一个示例代码:

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
        }
    }
}

Here is the solution to iterate over the list.这是迭代列表的解决方案。 Just cast to IEnumerable .只需投射到IEnumerable Don't forget to include using System.Collections;不要忘记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
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM