Get value of a variable using its name in a string

北城余情 提交于 2019-12-11 03:33:24

问题


I want to get the value of a variable from its name.

To clarify, an XML document delivers the variable name as a string; I want to get the value.

Something like this:

string bublegumA = "strawberry";
string bubblegumB = "banana";   

//get which variable from the XML

string fromXML = "bubblegumB";

string output = getValue(fromXML);

//it should return "banana"

回答1:


Basically, this is an application of reflection:

This should work, if it's a field:

var value = targetObject.GetType().GetField(fromXml).GetValue(targetObject, null);

So if your class is:

public class MyClass
{
    public string BubblegumA = "Strawberry";
}

then in your main class:

public static void Main()
{
    MyClass targetObject = new MyClass();

    var value = targetObject.GetType().GetField("BubblegumA").GetValue(targetObject, null);

    //value should = Strawberry
}



回答2:


You can't do that. Variable names only exist at design time. Once it's compiled (without debugging symbols) the variable name is lost.

But you can do this:

var myValues = new Dictionary<string, string>();
myValues["bublegumA"] = "strawberry";
myValues["bublegumB"] = "banana";

string output = myValues["bublegumB"]; // "banana"

You could also use an ExpandoObject if you don't like the dictionary syntax for setting properties, though you still have cast it to a dictionary to get an value by name:

dynamic myValues = new ExpandoObject();
myValues.bublegumA = "strawberry";
myValues.bublegumB = "banana";

string output1 = myValues.bublegumB; // "banana"
string output2 = (string)((IDictionary<string, object>)myValues)["bublegumB"]; // "banana"


来源:https://stackoverflow.com/questions/16181118/get-value-of-a-variable-using-its-name-in-a-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!