是否可以将字符串转换为代码?
例如,而不是:
string foo = "bar";
...
switch(foo){
case "bar":
pictureBox.Image = Project.Properties.Resources.bar;
break;
...
}
有没有一种方法可以简单地:
string foo = "bar"
pictureBox.Image = Project.Properties.Resources.<foo string goes in here>;
我希望这个例子有意义。
最佳答案
您正在尝试做的事情在 C# 中称为“反射”。您可以在 StackOverflow 中找到一个带有代码示例的帖子:Get property value from string using reflection in C#
编辑:这是示例
string foo = "bar";
var resources = Project.Properties.Resources;
object o = resources.GetType().GetProperty(foo).GetValue(resources, null);
if (o is System.Drawing.Image) {
pictureBox.Image = (System.Drawing.Image) o;
}
关于c# - 如何将字符串转换为代码? (C#),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27873562/