问题
Using C#, could I able to access a content of a variable whose name is stored in another string variable
eg.
string str ="ABCDEFG";
string variable = "str";
Here could i access value of string str using var????
回答1:
you probably can, but that's too complicated. Have you thought of using the Dictionary class?
Dictionary<string,string> myDictionary = new Dictionary<string,string>();
myDictionary["str"] = "ABCDEF";
var valueinstr = myDictionary["str"];
回答2:
Yes you can by using reflection.
var fieldInfo = this.GetType().GetField(var);
string theValue = (string) fieldInfo.GetValue(this);
Note that in your sample var
is a keyword so you cannot use it as a name for a variable.
With the reflection approach you get an object that describes the property, then you use it to retrieve the value from a specific instance of a class. If your property is not public then you will have to specify the correct BindingFlags when you get the PropertyInfo. If you are using a variable like in your example then you need to retrieve a FieldInfo object (another example).
来源:https://stackoverflow.com/questions/12119232/access-value-of-variable-whose-name-is-stored-in-another-variable