繁体   English   中英

使用LookUpEdit的PropertyInfo.SetValue()中的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。 为什么要使用这种丑陋的方式修改对象属性?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM