gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 19:06:14 24 4
gpt4 key购买 nike

我在 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 中的方法?

最佳答案

两者都是正确的:)

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

and how can one distinguish between loading the "this" reference and loading the first formal parameter to a method in IL?

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

关于c# - 用于访问只读字段的 MSIL 代码导致 ldarg.0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27143272/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com