vendredi 15 mars 2019

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.

I iterate over all properties in the object with myObject.GetType().GetProperties() and search for properties which are from type IList.

I can identify the IList-properties and would like to iterate over the list. But there is my problem. I can't cast the listProperty (which is of type object) into generic list. 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>...

Cast into IList<object> is always 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
        }
    }
}





Aucun commentaire:

Enregistrer un commentaire