【问题标题】:property.GetValue(this, null) leads to "Object does not match target type"property.GetValue(this, null) 导致“对象与目标类型不匹配”
【发布时间】:2023-03-05 12:57:01
【问题描述】:

我有一个这样的数据库类

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); 它崩溃了,我得到:

“System.Reflection.TargetException”类型的未处理异常 发生在 mscorlib.dll 中

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

我在这里错过了什么?

【问题讨论】:

    标签: c# sql database winforms


    【解决方案1】:

    你必须改变这条线

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

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

    GetValue 的第一个参数需要目标实例来获取值。所以当你说this运行时抛出异常说this中不存在这样的属性。

    【讨论】:

    • 噢!非常感谢! :)
    • 我知道,必须等 10 分钟 :)
    • @SriramSakthivel,我有类似的情况,我有 2 个类,其中包含 ReferenceTypes,但我的 GetValue() 第一次工作,第二次失败。你能帮忙吗
    • @CSharped 失败是什么意思?以什么方式失败,有什么例外吗?我建议您使用失败的代码提出新问题。如果你想让我看的话,你可以把它链接在这里。谢谢
    【解决方案2】:

    试试这个

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多