代码之家  ›  专栏  ›  技术社区  ›  Anemoia

.NET IL属性设置程序

  •  1
  • Anemoia  · 技术社区  · 14 年前

    考虑这个类:

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

    现在,当我去查看编译器为 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)参数中?因为方法/属性设置器只接受一个参数。。。

    吸气剂也是如此:

    .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 把它还回去?:)

    谢谢。

    -蛇

    1 回复  |  直到 14 年前
        1
  •  4
  •   Jon Skeet    14 年前

    对于设定者:

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

    对于getter,我不知道为什么有局部变量。。。调试器支持吗?当然是以优化模式编译的( /o+ /debug- 从命令行)删除本地变量。