What are 'closures' in .NET?

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

    Closures are functional values that hold onto variable values from their original scope. C# can use them in the form of anonymous delegates.

    For a very simple example, take this C# code:

        delegate int testDel();
    
        static void Main(string[] args)
        {
            int foo = 4;
            testDel myClosure = delegate()
            {
                return foo;
            };
            int bar = myClosure();
    
        }
    

    At the end of it, bar will be set to 4, and the myClosure delegate can be passed around to be used elsewhere in the program.

    Closures can be used for a lot of useful things, like delayed execution or to simplify interfaces - LINQ is mainly built using closures. The most immediate way it comes in handy for most developers is adding event handlers to dynamically created controls - you can use closures to add behavior when the control is instantiated, rather than storing data elsewhere.

提交回复
热议问题