我试图将变量的名称作为字符串返回。
所以如果变量是var1,我想返回字符串“var1”。
有什么办法可以做到这一点吗?我听说 Reflection 可能是在正确的方向。
编辑:
我本质上是试图使有组织的树 View 的实现更简单。
我有一个方法,你给两个字符串:rootName 和 subNodeText。 rootName 恰好是一个变量的名称。对此方法的调用来自此变量的 with 块。我希望用户能够调用 Method(.getVariableAsString, subNodeText) 而不是 Method("Variable", subNodeText)。想要以编程方式获取它的原因是可以简单地复制和粘贴此代码。我不想每次变量被命名为异常时都必须调整它。
Function aFunction()
Dim variable as Object '<- This isn't always "variable".
Dim someText as String = "Contents of the node"
With variable '<- Isn't always "variable". Could be "var", "v", "nonsense", etc
'I want to call this
Method(.GetName, someText)
'Not this
Method("Variable",someText)
End With
End Function
最佳答案
现在可以从 VB.NET 14 ( More information here ) 开始:
Dim variable as Object
Console.Write(NameOf(variable)) ' prints "variable"
编译您的代码时,您分配的所有变量名称都会更改。无法在运行时获取局部变量名称。但是,您可以使用 System.Reflection.PropertyInfo 获取类的属性名称
Dim props() As System.Reflection.PropertyInfo = Me.GetType.GetProperties(BindingFlags.Public Or _
BindingFlags.Instance Or BindingFlags.DeclaredOnly)
For Each p As System.Reflection.PropertyInfo In props
Console.Write(p.name)
Next
关于vb.net - 尝试以字符串形式获取变量名 VB.NET,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14531021/