C# 匿名方法本质

匿名方法

匿名方法与具名方法在本质上是相同的,使用匿名方法后编译器在定义匿名方法的类的外部动态生成具名方法。

  /// <summary>
    /// 定义委托
    /// </summary>
  delegate void DoWorkDelegate();

class Program
    {
        static void Main(string[] args)
        {
            //具名方法的委托
            DoWorkDelegate doWorkName=new DoWorkDelegate (DoWorkWithName);
           
            //匿名方法的委托
            DoWorkDelegate  doWorkNoName=delegate()
            {
                Console.WriteLine("DoWorkDelegate AnonymousDelegate");
            };

            Console.Read();
            
        }

        /// <summary>
        /// 具名方法
        /// </summary>
        static void DoWorkWithName()
        {
            Console.WriteLine("DoWorkDelegate AnonymousDelegate");
        }
    }

使用ildasm打开程序集后可以看到:
Program下有两个静态方法
.method private hidebysig static void  DoWorkWithName() cil managed
{
  // 代码大小       13 (0xd)
  .maxstack  8
  IL_0000:  nop
  IL_0001:  ldstr      "DoWorkDelegate AnonymousDelegate"
  IL_0006:  call       void [mscorlib]System.Console::WriteLine(string)
  IL_000b:  nop
  IL_000c:  ret
} // end of method Program::DoWorkWithName

  '<Main>b__0' 为编译器在后台为匿名方法生成的静态方法
.method private hidebysig static void  '<Main>b__0'() cil managed
{
  .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 )
  // 代码大小       13 (0xd)
  .maxstack  8
  IL_0000:  nop
  IL_0001:  ldstr      "DoWorkDelegate AnonymousDelegate"
  IL_0006:  call       void [mscorlib]System.Console::WriteLine(string)
  IL_000b:  nop
  IL_000c:  ret
} // end of method Program::'<Main>b__0'

委托初始化产生的IL代码如下:

委托使用具名方法实例化:
 IL_0002:  ldftn      void AnonymousDelegateApp.Program::DoWorkWithName()
  IL_0008:  newobj     instance void AnonymousDelegateApp.DoWorkDelegate::.ctor(object,
                                                                                native int)

委托使用匿名方法实例化:
IL_0016:  ldftn      void AnonymousDelegateApp.Program::'<Main>b__0'()
IL_001c:  newobj     instance void AnonymousDelegateApp.DoWorkDelegate::.ctor(object,
                                                                                native int)

由此可见匿名方法与具名方法本质上没有任何区别,匿名方法只是编译器在后台动态产生了具名方法,使用匿名方法或具名方法实例化委托时,
两者产生的Il代码是完全一致的。







你可能感兴趣的:(C#)