【问题标题】:Get value of item in object by variable name通过变量名获取对象中项目的值
【发布时间】:2019-02-05 23:20:44
【问题描述】:

给定一些看起来像这样的对象:

public class MyObject 
{
    public int thing_1 { get; set; }
    public int thing_2 { get; set; }
    public int thing_3 { get; set; }
    ....
    public int thing_100 { get; set; }
}

我该怎么做这样的事情:

int valueINeed = GetValue(MyObject, 2);

哪个会调用...(这就是我需要帮助的地方)...

private int GetValue(MyObject, int find)
{
    return MyObject.thing_[find];
}

如果可以避免的话,我宁愿不要在 Switch 中逐行进行。

【问题讨论】:

  • 好点。我会清理的

标签: c#


【解决方案1】:

这可能会有所帮助:

var obj = new MyChildObject();
foreach(var prop in obj .GetType().GetProperties()) 
{
    if (prop.Name == "thing_" + find.ToString())
         return prop.GetValue(obj, null);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-13
    • 1970-01-01
    • 1970-01-01
    • 2013-10-08
    • 2017-10-27
    • 2021-06-16
    • 2019-07-08
    相关资源
    最近更新 更多