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);
}
说得好。我会把它清理干净