C# 如何将字符串值转换为对象属性名称
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19276475/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I convert string value to object property name
提问by LaRae White
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 中做这样的事情,有点让我想起在 JavaScript 中使用 eval() 函数或动态脚本和生成 HTML 可以轻松完成的事情。我有一个取自用户输入的字符串,比如说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;
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# 中有一种方法可以做这样的事情吗?可能使用反射?我试过了,但我总是返回一个不能真正解决我的问题的对象。
采纳答案by Mister Epic
Reflection is the right tool:
反射是正确的工具:
PropertyInfo pinfo = typeof(YourType).GetProperty("YourProperty");
object value = pinfo.GetValue(YourInstantiatedObject, null);