What are 'closures' in .NET?

前端 未结 12 1908
执念已碎
执念已碎 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<int, int> 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.

    0 讨论(0)
  • 2020-11-21 14:25

    A closure is a function, defined within a function, that can access the local variables of it as well as its parent.

    public string GetByName(string name)
    {
       List<things> theThings = new List<things>();
      return  theThings.Find<things>(t => t.Name == name)[0];
    }
    

    so the function inside the find method.

     t => t.Name == name
    

    can access the variables inside its scope, t, and the variable name which is in its parents scope. Even though it is executed by the find method as a delegate, from another scope all together.

    0 讨论(0)
  • 2020-11-21 14:26

    Basically closure is a block of code that you can pass as an argument to a function. C# supports closures in form of anonymous delegates.

    Here is a simple example:
    List.Find method can accept and execute piece of code (closure) to find list's item.

    // Passing a block of code as a function argument
    List<int> ints = new List<int> {1, 2, 3};
    ints.Find(delegate(int value) { return value == 1; });
    

    Using C#3.0 syntax we can write this as:

    ints.Find(value => value == 1);
    
    0 讨论(0)
  • 2020-11-21 14:27

    A closure aims to simplify functional thinking, and it allows the runtime to manage state, releasing extra complexity for the developer. A closure is a first-class function with free variables that are bound in the lexical environment. Behind these buzzwords hides a simple concept: closures are a more convenient way to give functions access to local state and to pass data into background operations. They are special functions that carry an implicit binding to all the nonlocal variables (also called free variables or up-values) referenced. Moreover, a closure allows a function to access one or more nonlocal variables even when invoked outside its immediate lexical scope, and the body of this special function can transport these free variables as a single entity, defined in its enclosing scope. More importantly, a closure encapsulates behavior and passes it around like any other object, granting access to the context in which the closure was created, reading, and updating these values.

    0 讨论(0)
  • 2020-11-21 14:30

    Closures are chunks of code that reference a variable outside themselves, (from below them on the stack), that might be called or executed later, (like when an event or delegate is defined, and could get called at some indefinite future point in time)... Because the outside variable that the chunk of code references may gone out of scope (and would otherwise have been lost), the fact that it is referenced by the chunk of code (called a closure) tells the runtime to "hold" that variable in scope until it is no longer needed by the closure chunk of code...

    0 讨论(0)
  • 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<int, int> 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<int, int> multiplier = n => n * factor;
    factor = 10;
    Console.WriteLine (multiplier (3)); // 30
    
    0 讨论(0)
提交回复
热议问题