Strange decompiled code from event subscribe code in a generic class

匿名 (未验证) 提交于 2019-12-03 01:22:02

问题:

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:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!