【问题标题】:MSIL code for accessing a readonly field results in ldarg.0用于访问只读字段的 MSIL 代码导致 ldarg.0
【发布时间】:2014-11-26 07:15:30
【问题描述】:

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

IL_0024:  ldarg.0
IL_0025:  ldfld      string MyAssembly.MyClass.TestClass::A

我的自然假设是 this 用于在访问成员字段时加载“this”引用,而这个问题也证实了这一点:Why do I have to do ldarg.0 before calling a field in MSIL?

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

对此行为的正确解释是什么?以及如何区分加载“this”引用和加载第一个形式参数到 IL 中的方法?

【问题讨论】:

    标签: c# .net cil


    【解决方案1】:

    两者都是正确的:)

    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);
    }
    

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

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

    【讨论】:

      【解决方案2】:

      所有实例方法都将第一个参数作为类实​​例本身。这是隐式完成的,因此您在调用方法时不必传递它。

      鉴于this 是一个方法参数,您需要使用ldarg.0this 实例推送到评估堆栈。

      【讨论】:

        猜你喜欢
        • 2010-12-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-01-03
        • 1970-01-01
        • 2016-07-10
        • 1970-01-01
        • 2012-04-05
        相关资源
        最近更新 更多