.NET IL 属性设置器
考虑这个类:
public class Foo
{
// Fields
private string _bar;
// Properties
private string Bar
{
get
{
return this._bar;
}
set
{
this._bar = value;
}
}
}
现在,当我查看编译器发出的 IL 代码中的 Bar
属性设置器时:
.method private hidebysig specialname instance void set_Bar(string 'value') cil managed
{
.maxstack 8
L_0000: nop
L_0001: ldarg.0
L_0002: ldarg.1
L_0003: stfld string ConsoleApplication2.Program/Foo::_bar
L_0008: ret
}
为什么它会执行 ldarg.0
?第一个(索引 0)参数中的内容是什么?由于方法/属性 setter 仅接受 1 个参数...
getter 也是如此:
.method private hidebysig specialname instance string get_Bar() cil managed
{
.maxstack 1
.locals init (
[0] string CS$1$0000)
L_0000: nop
L_0001: ldarg.0
L_0002: ldfld string ConsoleApplication2.Program/Foo::_bar
L_0007: stloc.0
L_0008: br.s L_000a
L_000a: ldloc.0
L_000b: ret
}
为什么使用 .locals init
?为什么是 ldarg.0 ?为什么它不对支持字段执行 ldfld 并返回它? :)
Consider this class:
public class Foo
{
// Fields
private string _bar;
// Properties
private string Bar
{
get
{
return this._bar;
}
set
{
this._bar = value;
}
}
}
Now when I go and look in the IL code emitted by the compiler for the setter of the Bar
property:
.method private hidebysig specialname instance void set_Bar(string 'value') cil managed
{
.maxstack 8
L_0000: nop
L_0001: ldarg.0
L_0002: ldarg.1
L_0003: stfld string ConsoleApplication2.Program/Foo::_bar
L_0008: ret
}
Why does it do a ldarg.0
? WHAT is located in first (index 0) argument? Since the method/property setter only takes 1 argument...
The same goes for the getter:
.method private hidebysig specialname instance string get_Bar() cil managed
{
.maxstack 1
.locals init (
[0] string CS$1$0000)
L_0000: nop
L_0001: ldarg.0
L_0002: ldfld string ConsoleApplication2.Program/Foo::_bar
L_0007: stloc.0
L_0008: br.s L_000a
L_000a: ldloc.0
L_000b: ret
}
Why the .locals init
? Why the ldarg.0 ? Why doesn't it do a ldfld
of the backing field and just return that? :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对于设置器:
任何实例成员都有一个隐式的“this”参数 - 基本上,这就是正在加载的参数。尝试将其变成静态属性,您会发现它消失了。
对于吸气剂,我不确定为什么有局部变量......调试器支持也许?当然,以优化模式(从命令行
/o+ /debug-
)编译它会消除局部变量。For the setter:
Any instance member has an implicit "this" parameter - that's what's being loaded, basically. Try turning it into a static property and you'll see it go away.
For the getter, I'm not sure why there's the local variable... debugger support perhaps? Certainly compiling it in optimized mode (
/o+ /debug-
from the command line) gets rid of the local variable.