【问题标题】:LINQ - Accessing a column with the column name as a string parameterLINQ - 使用列名作为字符串参数访问列
【发布时间】:2013-10-30 22:53:09
【问题描述】:

(类似于this question

我有名为“问题”和“最终数字”的表格:

问题(QuestionID、文本、FinalFiguresColumnName)
FinalFigures(FinalFigureID、TotalDays、TotalCost 等)

'FinalFiguresColumnName' 将具有诸如“TotalDays”、“TotalCost”等值。是否有一种简单的方法可以遍历一组问题并将“Text”值保存到“FinalFigures”上的相应列名桌子?

即。而不是:

var item = new FinalFigure();
item.TotalDays = "x";

我需要:

var item = new FinalFigure();
// access the column 'TotalDays' with its name as a string, not a property

【问题讨论】:

    标签: c# sql linq


    【解决方案1】:

    可以使用一点反射,通过属性的字符串名称获取属性值,而不是直接访问。

    var value = (int)item.GetType().GetProperty("TotalDays").GetValue(item);
    

    要设置值,只需调用 SetValue();

    item.GetType().GetProperty("TotalDays").SetValue(item, value);
    

    【讨论】:

      猜你喜欢
      • 2020-09-12
      • 2015-08-14
      • 2022-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多