vendredi 14 décembre 2018

C# Reflection - SetValue by path to property

I'd like to update value in any public property by specifying a dots delimited path to it.

But whenever I call my method I receive an error in line:

pi.SetValue(instance, value1, null);

Error message:

Object does not match target type.

My method:

private void SetPathValue(object instance, string path, object value)
{
    string[] pp = path.Split('.');
    Type t = instance.GetType();
    for (int i = 0; i < pp.Length; i++)
    {
        PropertyInfo pi = t.GetProperty(pp[i]);
        if (pi == null)
        {
            throw new ArgumentException("Properties path is not correct");
        }
        else
        {
            instance = pi.GetValue(instance, null);
            t = pi.PropertyType;
            if (i == pp.Length - 1)//last
            {
               // Type targetType = IsNullableType(pi.PropertyType) ? Nullable.GetUnderlyingType(pi.PropertyType) : pi.PropertyType;
                var value1 = Convert.ChangeType(value, instance.GetType());
                pi.SetValue(instance, value1, null);//ERROR
            }
        }
    }
}

private static bool IsNullableType(Type type)
{
    return type.IsGenericType && type.GetGenericTypeDefinition().Equals(typeof(Nullable<>));
}





Aucun commentaire:

Enregistrer un commentaire