property.GetValue(this, null) 导致 "对象不匹配目标类型" 错误。

11

我有一个像这样的数据库类

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 作为它的数据源,我通过以下方式将网格视图中选择的行检索为一个数据库类实例:
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); 中,程序崩溃并显示以下错误信息:

未经处理的异常类型 'System.Reflection.TargetException' 出现在 mscorlib.dll 中

附加信息:对象不符合目标类型。

我错过了什么?

2个回答

21

你需要将这一行从原来的代码中修改为:

 object obj = property.GetValue(this, null);  
object obj = property.GetValue(currentObject, null);

GetValue 的第一个参数需要目标实例以获取其值。因此,当您使用 this 时,运行时会抛出异常,指示在 this 中不存在此属性。


糟糕!非常感谢! :) - Dimo
我知道,必须等待10分钟 :) - Dimo
@SriramSakthivel,我有一个类似的情况,我有两个包含ReferenceTypes的类,但是我的GetValue()第一次运行成功,第二次失败了。你能帮忙吗? - CSharped
@CSharped 你所说的“失败”是指什么?以何种方式失败,是否有任何异常?我建议你提出新问题,并附上导致失败的代码。如果你想让我看一下,可以在这里链接。谢谢。 - Sriram Sakthivel

6

试试这个

foreach (PropertyInfo property in currentObject.GetType().GetProperties())
{         
    var name = property.Name;
    object obj = property.GetValue(currentObject, null);    
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接