用于访问只读字段的MSIL代码导致ldarg.0

lys*_*cid 1 .net c# cil

我在C#中有一个访问readonly字段的简单方法:

IL_0024:  ldarg.0
IL_0025:  ldfld      string MyAssembly.MyClass.TestClass::A
Run Code Online (Sandbox Code Playgroud)

我自然的假设是,这用于在访问成员字段时加载"this"引用,这个问题也证实:为什么在调用MSIL中的字段之前我必须执行ldarg.0?

但是,ldarg的文档提到它用于加载传递给方法的参数.

这种行为的正确解释是什么?如何区分加载"this"引用和将第一个形式参数加载到IL中的方法?

Jon*_*eet 5

两者都是正确的:)

this值作为第一个"不可见"参数传递给实例方法,因此在实例方法中,ldarg.0"加载this值".

如果编写使用不同参数的方法,则可以看到差异.例如:

static void StaticMethod(int x)
{
    // This uses ldarg.0
    Console.WriteLine(x);
}

void InstanceMethod(int x)
{
    // This uses ldarg.1
    Console.WriteLine(x);
}
Run Code Online (Sandbox Code Playgroud)

如何区分加载"this"引用和将第一个形式参数加载到IL中的方法?

通过检查上面的内容,基本上 - 如果它是一个实例方法,则ldarg.0加载隐式this值.否则,它会加载第一个形式参数值.