PropertyInfo.SetValue() 中带有 LookUpEdit 的 C# TargetException

C# TargetException in PropertyInfo.SetValue() with LookUpEdit

我有一个 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" 的字符串,所以这就是为什么我要拆分

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

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。为什么要使用这种丑陋的方式来修改对象属性?