What are 'closures' in .NET?

前端 未结 12 1947
执念已碎
执念已碎 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: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 ints = new List {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);
    

提交回复
热议问题