samedi 2 avril 2022

Convert List

I'm trying to convert a string delimited by a comma to a list of some type.

private static void SetPropertyValue(this object obj, PropertyInfo propInfo, object value)
{
    if (propInfo.PropertyType != typeof(string) && typeof(IEnumerable).IsAssignableFrom(propInfo.PropertyType))
    {
        var listType = propInfo.PropertyType.GetCollectionType();
        var listValue = value.ToString().Split(',').Select(x => Convert.ChangeType(x, listType, null)).ToList();

        propInfo.SetValue(obj, listValue, null);
    }
    
    //....
}

public static Type GetCollectionType(this Type type)
{
    foreach (Type interfaceType in type.GetInterfaces())
    {
        if (interfaceType.IsGenericType &&
            interfaceType.GetGenericTypeDefinition()
            == typeof(IList<>))
        {
            return type.GetGenericArguments()[0];
        }
    }

    throw new ArgumentException("Message is irrelevant");
}

Splitting the string and converting each value with Convert.ChangeType works well, but creates a List<object>. I need some way of generating a List<PropType> in order for the SetValue call to work correctly.

If you were to run this code with a List<string> property, you would receive an ArgumentException as the List<object> cannot be converted to a List<string>.





Aucun commentaire:

Enregistrer un commentaire