为什么CLR为匿名方法创建新类? [英] Why does CLR create new class for anonymous method?

查看:73
本文介绍了为什么CLR为匿名方法创建新类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的项目中同样使用匿名函数。直到知道我在想,C#编译器仅使用同一类中用于匿名方法的代码生成一个方法。但是,在IL中反编译此代码后,我看到CLR创建了一个新类。

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. But, after decompiling this code in IL, I saw that CLR created a new class.

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));
}

此处是 Main 方法的反编译IL代码:

Here is decompiled IL code of the Main method:

.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    
   ...
}


推荐答案

如果没有什么可以捕获的,则C#如果闭包中有变量,则编译器将在类中创建私有方法-将创建内部类。

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.

第12章-委托和Lambda表达式

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

这篇关于为什么CLR为匿名方法创建新类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆