What are 'closures' in .NET?

前端 未结 12 1929
执念已碎
执念已碎 2020-11-21 13:53

What is a closure? Do we have them in .NET?

If they do exist in .NET, could you please provide a code snippet (preferably in C#) explaining it?

12条回答
  •  时光说笑
    2020-11-21 14:21

    If you are interested in seeing how C# implements Closure read "I know the answer (its 42) blog"

    The compiler generates a class in the background to encapsulate the anoymous method and the variable j

    [CompilerGenerated]
    private sealed class <>c__DisplayClass2
    {
        public <>c__DisplayClass2();
        public void b__0()
        {
           Console.Write("{0} ", this.j);
        }
        public int j;
    }
    

    for the function:

    static void fillFunc(int count) {
        for (int i = 0; i < count; i++)
        {
            int j = i;
            funcArr[i] = delegate()
                         {
                             Console.Write("{0} ", j);
                         };
        } 
    }
    

    Turning it into:

    private static void fillFunc(int count)
    {
        for (int i = 0; i < count; i++)
        {
            Program.<>c__DisplayClass1 class1 = new Program.<>c__DisplayClass1();
            class1.j = i;
            Program.funcArr[i] = new Func(class1.b__0);
        }
    }
    

提交回复
热议问题