Access value of variable whose name is stored in another variable

泄露秘密 提交于 2019-12-13 07:38:59

问题


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

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