问题
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