2

考虑这个类:

public class Foo
{
    // Fields
    private string _bar;

    // Properties
    private string Bar
    {
        get
        {
            return this._bar;
        }
        set
        {
            this._bar = value;
        }
    }
}

现在,当我查看编译器为Bar属性设置器发出的 IL 代码时:

.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)参数中?由于方法/属性设置器只需要 1 个参数...

吸气剂也是如此:

.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支持字段并返回它?:)

4

1 回答 1

4

对于二传手:

任何实例成员都有一个隐含的“this”参数——基本上就是正在加载的内容。试着把它变成一个静态属性,你会看到它消失了。

对于吸气剂,我不确定为什么会有局部变量......也许是调试器支持?当然,以优化模式(/o+ /debug-从命令行)编译它会摆脱局部变量。

于 2010-11-15T13:23:18.367 回答