Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/318.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 按变量名获取对象中项的值_C# - Fatal编程技术网

C# 按变量名获取对象中项的值

C# 按变量名获取对象中项的值,c#,C#,给定一些看起来像这样的对象: 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); 我该如何做这样

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

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);
我该如何做这样的事情:

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);
这就叫。。。(这就是我需要帮助的地方)


如果可以避免的话,我不想一行一行地切换。

根据您的实际情况,您可能想做一些比直接反射(可能很慢)更复杂的事情

动态语言运行时(支持
动态
)可能很有用,对此问题进行了一些讨论:

还有一个There引用了NuGet包。使用它,您的
GetValue()
例程现在只需:

public class MyObject
{
    public int thing_1 { get; set; }
    ...
    int GetValue(int find)
    {
       return (int)Dynamic.InvokeGet(this, "thing_" + find.ToString());
    }
}
这可能有助于:

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

说得好。我会把它清理干净