mardi 21 juin 2016

How to use reflection to get the number of items in a list

I have a class that has a few List<T> properties. I need to be able to dynamically determine the size of a given list.

Below is the code that I have so far. How can I get rid of the switch statement and just have this as one general statement? I would love to cast to List<T>, but that doesn't work.

switch (Inf.GetType()
            .GetProperty(propertyName)
            .GetValue(Inf)
            .GetType()
            .UnderlyingSystemType.GenericTypeArguments[0]
            .Name)
        {
            case "String":
                dynamicListCount = ((List<string>)Inf.GetType().GetProperty(propertyName).GetValue(Inf)).Count;
                break;
            case "Int32":
                dynamicListCount = ((List<Int32>)Inf.GetType().GetProperty(propertyName).GetValue(Inf)).Count;
                break;
            default:
                throw new Exception("Unknown list type");
        }





Aucun commentaire:

Enregistrer un commentaire