What are 'closures' in .NET?

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

    Just out of the blue,a simple and more understanding answer from the book C# 7.0 nutshell.

    Pre-requisit you should know :A lambda expression can reference the local variables and parameters of the method in which it’s defined (outer variables).

        static void Main()
        {
        int factor = 2;
       //Here factor is the variable that takes part in lambda expression.
        Func multiplier = n => n * factor;
        Console.WriteLine (multiplier (3)); // 6
        }
    

    Real part:Outer variables referenced by a lambda expression are called captured variables. A lambda expression that captures variables is called a closure.

    Last Point to be noted:Captured variables are evaluated when the delegate is actually invoked, not when the variables were captured:

    int factor = 2;
    Func multiplier = n => n * factor;
    factor = 10;
    Console.WriteLine (multiplier (3)); // 30
    

提交回复
热议问题