[英]property.GetValue(this, null) leads to “Object does not match target type”
我有这样的数据库类
class Database
{
[Browsable(false)]
public long Session { get; set; }
public string Förnamn { get; set; }
public string Efternamn { get; set; }
public string Mail { get; set; }
}
DataGridView使用BindingList作为它的数据源,我将gridview的选定行检索为数据库类实例,如下所示:
Database currentObject = (Database)dataGridView1.CurrentRow.DataBoundItem;
现在我试图循环遍历“currentObject”的属性,如下所示:
foreach (PropertyInfo property in currentObject.GetType().GetProperties())
{
var name = property.Name;
object obj = property.GetValue(this, null);
}
但是在线object obj = property.GetValue(this, null);
它崩溃了,我得到:
mscorlib.dll中出现未处理的“System.Reflection.TargetException”类型异常
附加信息:对象与目标类型不匹配。
我在这里错过了什么?
你必须改变这一行
object obj = property.GetValue(this, null);
至
object obj = property.GetValue(currentObject, null);
GetValue
第一个参数需要目标实例来获取值。 所以,当你说this
运行时抛出异常,说没有这样的属性中不存在this
。
试试这个
foreach (PropertyInfo property in currentObject.GetType().GetProperties())
{
var name = property.Name;
object obj = property.GetValue(currentObject, null);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.