Strange decompiled code from event subscribe code

2019-06-24 16:50发布

This simple class

public class Test<T>
{
    public static void A(Window wa, Window wb)
    {
        wa.Closed += (s, e) => wb.Close();
    }
}

Gets compiled to this (I'm using Reflector to decompile) :

public class Test<T>
{
    [CompilerGenerated]
    private sealed class <>c__DisplayClass1
    {
        public Window wb;

        public void <A>b__0(object s, EventArgs e)
        {
            this.wb.Close();
        }
    }

    public static void A(Window wa, Window wb)
    {
        wa.Closed += delegate(object s, EventArgs e)
        {
            base.wb.Close();
        };
    }
}

What is the meaning of base ? Why is <>c__DisplayClass1 generated if it's never used ? Is this a Reflector bug ?

Edit: Indeed, seems like Reflector optimisation isn't woking very well in this case, disabling the optimisation the decompiled code makes sense :

public class Test<T>
{
    public Test()
    {
        base..ctor();
        return;
    }

    public static void A(Window wa, Window wb)
    {
        <>c__DisplayClass1<T> CS$<>8__locals2;
        CS$<>8__locals2 = new <>c__DisplayClass1<T>();
        CS$<>8__locals2.wb = wb;
        wa.Closed += new EventHandler(CS$<>8__locals2.<A>b__0);
        return;
    }

    [CompilerGenerated]
    private sealed class <>c__DisplayClass1
    {
        // Fields
        public Window wb;

        public <>c__DisplayClass1()
        {
            base..ctor();
            return;
        }

        public void <A>b__0(object s, EventArgs e)
        {
            this.wb.Close();
            return;
        }
    }
}

1条回答
做自己的国王
2楼-- · 2019-06-24 17:14

Reflector is "optimising" the output to try to come up with what the C# might have looked like. I don't know where the "base" bit is coming from, admittedly... but the generated class is definitely being used.

Set the Reflector options to "unoptimised" and you'll see something more like an IL to C# direct conversion. Or just switch to IL and read it directly, if you want a pretty raw view.

查看更多
登录 后发表回答