2

有谁知道如何获取已声明变量的名称。例如:

Public Function returnName(variable as integer) as string

Dim [string] as string = string.empty 
[string] = variable.name 
return [string]

End Function

我已经看到它尝试了几次,大多数人说这是不可能的,解释说 IL 不存储传递的变量的名称,但是相信有一些可以追踪到名称的有形指针或引用似乎是合理的。谁能给我一些关于这个的标题。

为什么?这纯属个人研究。

4

2 回答 2

2

Reflection can get you the names of the method arguments, also local variables in the context of the method body, but that's where the buck stops. The only way to get them is by reading the debug information file, the .pdb that's generated for your program.

There's a good reason for that. One of the most important jobs performed by the jitter is to remove local variables from the generated machine code. And substitute them with cpu registers. It is a very important optimization that can make a great deal of difference in the speed of the code. Memory is slow, cpu registers are fast. That's an optimization that's performed in the release build of your program. Also very visible when you try to debug a release version of your program by attaching a debugger. You'll get a lot of warnings from the debugger, telling you that it doesn't know what you mean when you ask it to inspect a local variable. And also the downfall when using the .pdb file.

A backgrounder answer on the kind of optimizations performed by the jitter is available here.

于 2012-10-21T16:15:07.207 回答
1

检查方法可能如下所示:

Private Shared Function Check(Of T)(expr As Expression(Of Func(Of T))) As String
  Dim body = DirectCast(expr.Body, MemberExpression)
  Return body.Member.Name
End Function

variable假设它是类型Integer(您的示例) ,这就是您检查名称的方式:

Check(Of Integer)(Function() variable)

或者,通过类型推断,variable可以是任何类型:

Check(Function() variable)

完全适用于类级别的变量,本地人得到一个$VB$Local_前缀。

在这里问了同样的问题,但是在 C# 中。我从那里为 VB.NET 和您的特定示例采用了代码,并对其进行了测试。

于 2012-10-21T14:47:16.437 回答