尝试以字符串形式获取变量名 VB.NET
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14531021/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Trying To Get The Name Of A Variable as a String VB.NET
提问by ATD
I'm trying to return the name of a variable as a string.
我试图将变量的名称作为字符串返回。
So if the variable is var1, I want to return the string "var1".
所以如果变量是var1,我想返回字符串“var1”。
Is there any way I can do this? I heard that Reflection might be in the right direction.
有什么办法可以做到这一点吗?我听说 Reflection 可能是在正确的方向。
Edit:
编辑:
I'm essentially trying to make implementation of an organized treeview simpler. I have a method that you give two strings: rootName and subNodeText. The rootName happens to be the name of a variable. The call to this method is from within a with block for this variable. I want the user to be able to call Method(.getVariableAsString, subNodeText) instead of Method("Variable", subNodeText). The reason for wanting to get it programmatically is so that this code can be simply copied and pasted. I don't want to have to tweak it every time the variable is named something abnormal.
我本质上是试图使有组织的树视图的实现更简单。我有一个方法,你给两个字符串: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
回答by Edwin
This is now possible starting with VB.NET 14 (More information here):
现在可以从 VB.NET 14 开始(更多信息在这里):
Dim variable as Object
Console.Write(NameOf(variable)) ' prints "variable"
When your code is compiled, all the variable names you assign are changed. There is no way to get local variable names at runtime. You can, however, get names of the properties of a class by using System.Reflection.PropertyInfo
编译您的代码时,您分配的所有变量名称都会更改。无法在运行时获取局部变量名称。但是,您可以使用 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

