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

时间:2022-05-15 04:45:24

This question already has an answer here:

这个问题在这里已有答案:

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:

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

string input = "foo";
//magic to convert string value to be used
//as a object property name goes here maybe...
var success = cover.foo;

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.

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

1 个解决方案

#1


17  

Reflection is the right tool:

反思是正确的工具:

PropertyInfo pinfo = typeof(YourType).GetProperty("YourProperty");
object value = pinfo.GetValue(YourInstantiatedObject, null);

#1


17  

Reflection is the right tool:

反思是正确的工具:

PropertyInfo pinfo = typeof(YourType).GetProperty("YourProperty");
object value = pinfo.GetValue(YourInstantiatedObject, null);