为什么不能使用反射获得局部变量名称? [英] Why is it not possible to get local variable names using Reflection?

查看:114
本文介绍了为什么不能使用反射获得局部变量名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有这样的代码:

public class Program
{
    public static void Main()
    {
        string bar = "";
        int foo = 24;
    }
}

我可以使用以下方法获取在Main中声明的局部变量:

I can get the local variables declared in Main using:

var flag = BindingFlags.Static | BindingFlags.Public;
var fields = typeof(Program).GetMethod("Main", flags).GetMethodBody().LocalVariables;

这将返回一个IList<LocalVariableInfo>

This returns a IList<LocalVariableInfo> and the LocalVariableInfo has only three properties: IsPinned,LocalIndex and LocalType.So there is no Name property exists.

我想知道的是您可以在生成的IL code中看到变量名称:

What I'm wondering is that you can see the variable names in the generated IL code:

.method public hidebysig static void  Main() cil managed
{
  .entrypoint
  // Code size       11 (0xb)
  .maxstack  1
  .locals init ([0] string bar,
           [1] int32 foo)
  IL_0000:  nop
  IL_0001:  ldstr      ""
  IL_0006:  stloc.0
  IL_0007:  ldc.i4.s   24
  IL_0009:  stloc.1
  IL_000a:  ret
} // end of method Program::Main

,但是不可能使用Reflection来获取它们.是因为局部变量没有名称,并且只能通过其索引访问它们(如果这样,ILDASM.exe如何显示名称?),或者因为没有实现这样的功能?或者,如果可以使用其他方式,那么问题将是 如何 ?

but it is not possible to get them using Reflection.Is it because local variables don't have a name and they are only accessed by their indices (if so how the ILDASM.exe shows the names?), or because such feature is not implemented? Or if it is possible using another way then the question would be, how?

注意:我见过一些问题,例如以及大多数问题其中的一个正在使用Expressions来获取变量名.如果我想获取所有本地变量,包括由编译器生成的临时变量,那将无法正常工作.

Note: I have seen some questions like this and most of them is using Expressions to get variable name. It doesn't work if I would like to get all locals including temporary variables that generated by the compiler.

推荐答案

您必须区分人类可读的基于文本的CLI形式和计算机可读的CLI编译形式.

You have to differentiate between the human-readable text-based form of CLI and the machine-readable compiled form of CLI.

在文本CLI中,局部变量确实可以具有名称(请参见ECMA-335的II.15.4.1.3节,如Damien的回答所述).

In text CLI, local variables indeed can have names (see §II.15.4.1.3 of ECMA-335, as explained in Damien's answer).

但是以二进制形式,局部变量没有名称.为此,请参见§II.23.2.6,其中指定了方法的局部变量签名(其所有局部变量的列表)的二进制格式.而且它不包含任何变量名:

But in the binary form, local variables don't have names. For that, look at §II.23.2.6, where the binary format for a method's local variable signature (list of all its local variables) is specified. And it doesn't contain any mention of variable names:

因此,如果某些工具想知道局部变量的原始名称,则必须查看PDB文件中包含的调试信息.如果不存在,则无法找出名称.

So, if some tool wants to know the original name of a local variable, it has to look into the debugging information contained in the PDB file. If that's not present, there is no way to find out the name.

这篇关于为什么不能使用反射获得局部变量名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆