How can I convert a string to variable in c# or C++?
example (vb6):
dim a as string
dim b as开发者_StackOverflow中文版 string
b="halo"
a="b"
msgbox a
this should make a output = halo
is this possible?..,
thanks for the replies
Edit:
I first misunderstood your answer, but now I see (thx Gserg) that you wish to find a variable based on the name. In C# you have to do this via reflection. See the following code snippet, and make sure that you have referenced System.Reflection.
MyNamespace.MyClass cls = new MyNamespace.MyClass();
FieldInfo fi = cls.GetType().GetField("FieldName");
string value = (string)(fi.GetValue(null, null));
Console.Out.WriteLine(value);
Here I look up the field "FieldName" in that class and then I return the value of the field
See also the MSDN page for GetField http://msdn.microsoft.com/en-us/library/system.type.getfield(v=vs.71).aspx
You can not.
Reflection can't return name of local variable, only type and index.
Therefore, it's easiest to have a dictionary:
var d = new Dictionary<string, string>();
d.Add("b", "helo");
MessageBox.Show(d["b"]);
In C++ it is impossible. In C# it may be possible due to reflection (but I am not sure how).
精彩评论