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

标签 c# .net clr anonymous-methods

我在我的项目中同样使用匿名函数。直到知道我一直在想,C# 编译器只使用用于同一类 中的匿名方法的代码生成一个方法。但是,在 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));
}

下面是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    
   ...
}

最佳答案

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

详见 Chapter 12 - Delegates and Lambda Expressions

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

关于c# - 为什么 CLR 为匿名方法创建新类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23298957/

相关文章:

c# - C# 中的列表和列表的值

c# - 在没有进程引用它后删除 "in use"文件

C# 长子串函数

c# - 下面的场景是如何分配内存的?我设法把它弄糊涂了

c# - Json 与 .NET 和 C#?

c# - 在从 C# 调用的 DLL 中使用 std::cout

.net - XMLDocument dispose - 为什么它不支持 IDisposable?

c# - 将 Enumerable.ToDictionary 与扩展方法一起使用时为 "CLR detected an Invalid Program"

c# - 默认情况下,CLR 会重用 LOH 中的对象吗?

c# - 在图片框上绘图时位置错误