【问题标题】:How to obtain the value of a specific property in DataRow (unknown) object using LINQ / Reflection?如何使用 LINQ / Reflection 获取 DataRow(未知)对象中特定属性的值?
【发布时间】:2020-12-20 12:53:21
【问题描述】:

如何获取变量的 RowData 属性中的特定行?我正在尝试获取“Id”。到目前为止,我尝试过的是 LINQ 或常规的 foreach 循环,但是我只能访问 GetType().GetProperties()。通过这些方法,我无法访问“Id”的值。

到目前为止我已经尝试过:

我尝试过像这样使用反射:

public void CommandClickHandler(CommandClickEventArgs<object> args)
{
    TabObj.Select(2);
    var IdOfModel = args.RowData.GetType().GetProperties().Single(pi => pi.Name == "Id").GetValue(args, null);
}

但这给了我错误“对象与目标类型不匹配”。

希望有人能帮忙!

提前致谢

【问题讨论】:

  • test.RowData.Id ?..
  • test.RowData.Id @RomanRyzhiy 他不能因为 RowData 的类型是 prolly object ...
  • 那是正确的,如果我使用 test.RowData.Id 我得到以下内容:GetType()、ToString()。 GetHashCode()
  • 而不是使用 Grid&lt;object&gt; 使用 Grid&lt;YourTypeProllyUser&gt; 然后你就可以像 Roman 写的那样使用它(因为那时 CommandClickEventArgs&lt;object&gt; 将变成 CommandClickEventArgs&lt;YourTypeProllyUser&gt; ,我想但应该在文档中说明)
  • 我不能这样做,因为页面是动态构建的。一定有可能以某种方式访问​​ Id 的值吗?

标签: c# linq loops foreach properties


【解决方案1】:

很清楚如果你把它拆开会发生什么。您将错误的参数传递给PropertyInfo.GetValue(object,arg[]),它应该是:

var obj = args.RowData;
var type = obj.GetType();
var IdOfModel = type.GetProperties().Single(pi => pi.Name == "Id").GetValue(obj, null);

或者干脆

dynamic obj = args.RowData;
var IdOfModel = obj.Id;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-16
    • 1970-01-01
    • 2022-01-15
    相关资源
    最近更新 更多