简体   繁体   English

为什么CLR为匿名方法创建新类?

[英]Why does CLR create new class for anonymous method?

I am using anonymous functions in my projects no less. 我在我的项目中同样使用匿名函数。 And till know I was thinking that, C# compiler generates just a method using the code used for the anonymous method in the same class . 直到知道我在想,C#编译器仅使用同一类中用于匿名方法的代码生成一个方法。 But, after decompiling this code in IL, I saw that CLR created a new class. 但是,在IL中反编译此代码后,我看到CLR创建了一个新类。

public class Comparer
{
    public delegate int Greater(int a, int b);

    public int Great(Greater greater, int a, int b)
    {
        return greater(a, b);
    }
}

static void Main(string[] args)
{
    int valueOfA = 11,
        valueOfB = 23,
        valueOfC = 42;

    Comparer comparer = new Comparer();

    Console.WriteLine("The greater is \t:{0}",
        comparer.Great(delegate(int a, int b)
        {
            int[] numbers = new int[] { a, b, valueOfC };
            return Math.Max(Math.Max(a, b), valueOfC);
        },
        valueOfA, valueOfB));
}

Here is decompiled IL code of the Main method: 这是Main方法的反编译IL代码:

.method private hidebysig static void  Main(string[] args) cil managed
{
  .entrypoint
  // Code size       65 (0x41)
  .maxstack  5
  .locals init ([0] int32 valueOfA,
           [1] int32 valueOfB,
           [2] class Ch04.Comparer comparer,
           [3] class Ch04.Program/'<>c__DisplayClass1' 'CS$<>8__locals2') // Here it is    
   ...
}

If there is nothing to capture it C# compiler will create private method in the class, if you have variables in closure - inner class will be created. 如果没有什么要捕获的,则C#编译器将在类中创建私有方法,如果您在闭包中有变量,则会创建内部类。

Covered in details in Chapter 12 - Delegates and Lambda Expressions 第12章-委托和Lambda表达式中有详细介绍

int local = 42;
...Where(value => {return true;})... // private method
...Where(value => { return value == local;})... // class 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM