如何将字符串值转换为对象属性名称 [英] How can I convert string value to object property name
问题描述
这是我第一次必须在C#/。NET中执行此类操作,这使我想起了可以使用eval()函数或动态编写脚本并生成HTML在JavaScript中轻松完成的操作。我有一个来自用户输入的字符串,可以说 string input = foo
。现在,我想使用值 foo
作为我拥有的对象的属性名称,例如 cover
这样:
this is my first time having to do something like this in C#/.NET and somewhat reminds me of what can easily be done in JavaScript using the eval() function or dynamically scripting and generating HTML. I have a string that is taken from user input, lets say string input = "foo"
. Now I would like to use the value "foo"
as the name of the property for an object I have, say cover
in such a way:
string input = "foo";
//magic to convert string value to be used
//as a object property name goes here maybe...
var success = cover.foo;
在C#中是否可以做这样的事情?可能使用反射?我已经尝试过,但是我总是会得到一个不能真正解决我问题的对象。
Is there a way in C# that I can do such a thing? Possibly using reflection? I've tried but I always am returned with an object that doesn't really solve my problem.
推荐答案
反射是正确的工具:
PropertyInfo pinfo = typeof(YourType).GetProperty("YourProperty");
object value = pinfo.GetValue(YourInstantiatedObject, null);
这篇关于如何将字符串值转换为对象属性名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!