mercredi 12 juin 2019

Using reflection to cast an object to List of custom type

I have following scenario:

I have compound object which includes lists in it, I want to pass a 'path' to it like - Result.CustomerList.Name

Result is an object that contains List of Customer, but also contains many other lists of different types. I want to get to the Names of the customers in this particular case.

What I have so far

    private static object GetPropertyValue(this object obj, string propertyPath)
    {
        var fullPath = propertyPath.Split('.');
        for (int i = 0; i <= fullPath.Length - 1; i++)
        {
            if (obj == null) { return null; }
            var part = fullPath[i];

            Type type = obj.GetType();
            PropertyInfo propInfo = type.GetProperty(part);

            if (propInfo == null)
            {
                //if its a list
                if (obj.GetType().GetInterfaces().Any(
                    k => k.IsGenericType
                    && k.GetGenericTypeDefinition() == typeof(IEnumerable<>)))
                {
                    //get list generic argument
                    var argumentType = obj.GetType().GetGenericArguments()[0];

                   //cast obj to List of argumentType


                }
                else return null;
            }

            obj = propInfo.GetValue(obj, null);
        }

        return obj;
    }

I cant get the syntax or how to cast to List or List it doesnt work or List

I dont understand what i have missing or how to do it.





Aucun commentaire:

Enregistrer un commentaire