C# 在c中通过属性名从类的对象动态获取值#
我想编写一个方法,该方法应该从指定属性的C# 在c中通过属性名从类的对象动态获取值#,c#,dynamic,C#,Dynamic,我想编写一个方法,该方法应该从指定属性的对象返回值 public class MyClass { public int a { get; set; } public int b { get; set; } public int c { get; set; } public int d { get; set; } } public int GetValue(string field) { MyClass obj=new MyClass();
对象
返回值
public class MyClass
{
public int a { get; set; }
public int b { get; set; }
public int c { get; set; }
public int d { get; set; }
}
public int GetValue(string field)
{
MyClass obj=new MyClass();
obj=FromDb(); //get value from db
dynamic temp=obj;
return temp?.field;
}
上面的代码只是为了演示我要找的东西
在这里,我想将属性
名称(即,根据我上面的代码,a/b/c/d)作为方法GetValue
的输入,它应该返回该属性的值
public class MyClass
{
public int a { get; set; }
public int b { get; set; }
public int c { get; set; }
public int d { get; set; }
}
public int GetValue(string field)
{
MyClass obj=new MyClass();
obj=FromDb(); //get value from db
dynamic temp=obj;
return temp?.field;
}
此代码正在成功编译,但在运行时它将搜索属性名字段
而不是字段变量的值
任何建议或解决方法都将不胜感激。您可以使用反射来获得价值:
public int GetValue(string field)
{
MyClass obj = new MyClass();
obj = FromDb(); //get value from db
var property = obj.GetType().GetProperty(field);
return (int)property.GetValue(obj);
}
您可以使用反射来获取值:
public int GetValue(string field)
{
MyClass obj = new MyClass();
obj = FromDb(); //get value from db
var property = obj.GetType().GetProperty(field);
return (int)property.GetValue(obj);
}
我也是这么建议的,但既然你的答案比我的答案先出现,我就投你的一票;)非常感谢你,我要尝试一下,只是担心性能会有什么影响?@TufanChand-是的,会有性能冲击。很难说它是否会影响您的应用程序。你可能会想衡量一下你的表现,确保你对它感到满意。@Sean,好的,明白了,我会处理好的。非常感谢你的帮助。我也是这么建议的,但因为你的答案比我的答案先出现,所以我只投了你的一票;)非常感谢你,我要尝试一下,只是担心性能会有什么影响?@TufanChand-是的,会有性能冲击。很难说它是否会影响您的应用程序。你可能会想衡量一下你的表现,确保你对它感到满意。@Sean,好的,明白了,我会处理好的。非常感谢你的帮助。