What are 'closures' in .NET?

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

    A closure is when a function is defined inside another function (or method) and it uses the variables from the parent method. This use of variables which are located in a method and wrapped in a function defined within it, is called a closure.

    Mark Seemann has some interesting examples of closures in his blog post where he does a paralel between oop and functional programming.

    And to make it more detailed

    var workingDirectory = new DirectoryInfo(Environment.CurrentDirectory);//when this variable
    Func read = id =>
        {
            var path = Path.Combine(workingDirectory.FullName, id + ".txt");//is used inside this function
            return File.ReadAllText(path);
        };//the entire process is called a closure.
    

提交回复
热议问题