试图将变量的名称作为字符串VB.NET

ATD*_*ATD 8 vb.net reflection variables var tostring

我正在尝试将变量的名称作为字符串返回.

所以如果变量是var1,我想返回字符串"var1".

有什么方法可以做到这一点吗?我听说反思可能是正确的方向.

编辑:

我基本上试图使有组织的树视图的实现更简单.我有一个方法,你给两个字符串: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
Run Code Online (Sandbox Code Playgroud)

小智 11

现在可以从VB.NET 14开始了(这里有更多信息):

Dim variable as Object
Console.Write(NameOf(variable)) ' prints "variable"
Run Code Online (Sandbox Code Playgroud)

编译代码时,会更改分配的所有变量名称.无法在运行时获取局部变量名称.但是,您可以使用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
Run Code Online (Sandbox Code Playgroud)