使用LookUpEdit的PropertyInfo.SetValue()中的C#TargetException

时间:2018-10-22 15:26:54

标签: c# devexpress

我有一个LookUpEdit控件,我需要通过反射将属性值设置为NullText,但是我得到了TargetException:

private static void SetObjectProperty(string propiedad, string valor, object obj)
    {
        if (obj.GetType() == typeof(LookUpEdit))
        {
            string[] vv = propiedad.Split('.');
            string prop = vv[0];
            string propType = vv[1];

            var p = obj.GetType().GetProperty(prop, BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
            PropertyInfo propertyInfo = p.PropertyType.GetProperty(propType);

            if (propertyInfo != null)
            {
                propertyInfo.SetValue(obj, valor, null);
            }     
        }
    }

我只能通过LookUpEdit控件获得异常。

“ propiedad”是一个包含“ Properties.NullText”的字符串,所以这就是为什么我要进行分割的原因

1 个答案:

答案 0 :(得分:0)

您应将具有嵌套属性的操作应用于相应的嵌套对象:

static void SetObjectProperty(object obj, string propertyPath, object value) {
    if(obj != null && obj.GetType() == typeof(LookUpEdit)) {
        string[] parts = propertyPath.Split('.');
        var rootInfo = typeof(LookUpEdit).GetProperty(parts[0], 
            BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
        object root = rootInfo.GetValue(obj); // obtaining a root
        var nestedInfo = rootInfo.PropertyType.GetProperty(parts[1]);
        if(nestedInfo != null) 
            nestedInfo.SetValue(root, value, null); // using root object
    }
}

PS。为什么要使用这种丑陋的方式修改对象属性?