PropertyInfo.SetValue参数异常 [英] PropertyInfo.SetValue Argument Exception

查看:97
本文介绍了PropertyInfo.SetValue参数异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试使用PropertyInfo.SetValue设置我的业务对象中的属性值时,会引发参数异常.

即使数据类型错误,也会引发参数

是否有一种方法可以将对象类型动态地强制转换为PropertyInfo对象的基础PropertyType,而不必显式测试FullName属性,如下所示?

选择 案例 prop.PropertyType.FullName

An argument exception is thrown when attempting to use PropertyInfo.SetValue to set the value of a property in my business objects.

The argument is thrown because of wrong data type, even though a valid cast could be made.

Is there a way to dynamically cast the object type into the underlying PropertyType of the PropertyInfo object without having to test the FullName property explicitly as show below?

Select Case prop.PropertyType.FullName

案例 "System.String"

Case "System.String"

prop.SetValue(obj,tbx.Text, 没有了 )

prop.SetValue(obj, tbx.Text, Nothing)

推荐答案

您如何初始化 prop 变量?如果您已缓存其值,则它可能位于与 obj 不同的程序集中.在这种情况下,将存在两个不同的 System.String 实例. >来自
prop = obj. GetType ().GetProperty("propName")
&tb>

而不是


GetType (objType).GetProperty("propName")
 


(或也错了)

<表border ="0" cellspacing ="0" width ="100%">
prop = GetType ("objTypeName").GetProperty("propName")
 

tbx.Text 也是如此.如果 tbx 确实与 obj 在另一个程序集中(例如宏或外接程序),则唯一选择是明确的强制转换.

如果还有其他原因导致您的错误,则应提供有关此片段的代码的更多信息.

祝您好运!

乔丹·约瑟夫(Jordan Jossifov)
How did you initialize the prop variable? If you have cached its value, it may reside in a different assembly than obj. In such a case, there will be two different instances of System.String.

The correct way to obtain a PropertyInfo from obj should be


prop = obj.GetType().GetProperty( "propName")
 


instead of


prop = GetType( objType).GetProperty( "propName")
 


or (also wrong)


prop = GetType( "objTypeName").GetProperty( "propName")
 


The same holds for tbx.Text. If tbx is really in a different assembly than obj (such as a macro or an add-in), the only choice is an explicit cast.

If there is another reason for your error, you should provide more information about the code surrounding this fragment.

Good luck!

Jordan Jossifov


这篇关于PropertyInfo.SetValue参数异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆