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 作为它的数据源,我将 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”类型的未处理异常

附加信息:对象与目标类型不匹配。

我在这里想念什么?

4

2 回答 2

21

你必须改变这条线

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

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

的第一个参数GetValue需要目标实例来获取值。因此,当您说this运行时抛出异常时说this.

于 2013-11-05T13:42:53.260 回答
6

试试这个

foreach (PropertyInfo property in currentObject.GetType().GetProperties())
{         
    var name = property.Name;
    object obj = property.GetValue(currentObject, null);    
}
于 2013-11-05T13:43:59.700 回答