[英]how to convert string to variable,vb6/ c#/c++?
How can I convert a string to variable in c# or C++?如何在 c# 或 C++ 中将字符串转换为变量?
example (vb6):示例(vb6):
dim a as string
dim b as string
b="halo"
a="b"
msgbox a
this should make a output = halo这应该使 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.我首先误解了您的答案,但现在我看到(thx Gserg)您希望根据名称找到一个变量。 In C# you have to do this via reflection.
在 C# 中,您必须通过反射来做到这一点。 See the following code snippet, and make sure that you have referenced System.Reflection.
请参阅以下代码片段,并确保您已引用 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在这里,我在 class 中查找字段“FieldName”,然后返回该字段的值
See also the MSDN page for GetFieldhttp://msdn.microsoft.com/en-us/library/system.type.getfield(v=vs.71).aspx另请参阅 GetFieldhttp://msdn.microsoft.com/en-us/library/system.type.getfield(v=vs.71).aspx的 MSDN 页面
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 .在 C++ 中是不可能的。 In C# it may be possible due to reflection (but I am not sure how).
在 C# 中,可能由于反射(但我不确定如何)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.