Why is it not possible to get local variable names using Reflection?

后端 未结 4 2333
走了就别回头了
走了就别回头了 2021-02-20 13:33

If I have a code like this:

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

相关标签:
4条回答
  • 2021-02-20 14:10

    I think this is because the variable name you see in ILDasm come from the pdb file, not from the assembly itself. If you want to get them, you'll need to read the pdb too.

    0 讨论(0)
  • 2021-02-20 14:17

    From MSDN:

    Local variable names are not persisted in metadata. In Microsoft intermediate language (MSIL), local variables are accessed by their position in the local variable signature.

    0 讨论(0)
  • 2021-02-20 14:25

    I think you're looking at a Debug build. The id part of the .locals declaration is optional - so there's no guarantee that the names are retained.

    See MS Partition II which describes the IL Metadata, section 15.4.1.3 for further details:

    MethodBodyItem ::= …
       .locals [ init ] ‘(’ LocalsSignature ‘)’
    LocalsSignature ::= Local [ ‘,’ Local ]*
    Local ::= Type [ Id ]
    
    0 讨论(0)
  • 2021-02-20 14:27

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

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

    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:

    LocalVarSig

    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.

    0 讨论(0)
提交回复
热议问题