What are 'closures' in .NET?

前端 未结 12 1907
执念已碎
执念已碎 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:22

    Func GetMultiplier(int a)
    {
         return delegate(int b) { return a * b; } ;
    }
    //...
    var fn2 = GetMultiplier(2);
    var fn3 = GetMultiplier(3);
    Console.WriteLine(fn2(2));  //outputs 4
    Console.WriteLine(fn2(3));  //outputs 6
    Console.WriteLine(fn3(2));  //outputs 6
    Console.WriteLine(fn3(3));  //outputs 9
    

    A closure is an anonymous function passed outside of the function in which it is created. It maintains any variables from the function in which it is created that it uses.

提交回复
热议问题