如何将字符串值转换为对象属性名称

LaR*_*ite 16 .net c# string reflection

这是我第一次在C#/ .NET中做这样的事情,并且有点让我想起使用eval()函数或动态脚本和生成HTML在JavaScript中可以轻松完成的事情.我说有一个从用户输入中获取的字符串string input = "foo".现在我想使用该值"foo"作为我拥有的对象的属性名称,cover以这种方式说:

string input = "foo";
//magic to convert string value to be used
//as a object property name goes here maybe...
var success = cover.foo;
Run Code Online (Sandbox Code Playgroud)

C#中有没有办法可以做这样的事情?可能使用反射?我已经尝试了,但我总是带着一个并没有真正解决问题的对象返回.

Mis*_*pic 20

反思是正确的工具:

PropertyInfo pinfo = typeof(YourType).GetProperty("YourProperty");
object value = pinfo.GetValue(YourInstantiatedObject, null);
Run Code Online (Sandbox Code Playgroud)

  • 谢谢,这是有效的,类似于上面评论中的建议,稍微调整一下:`var success = cover.GetType().GetProperty(input).GetValue(cover,null);` (4认同)