What are 'closures' in .NET?

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

    Here is a contrived example for C# which I created from similar code in JavaScript:

    public delegate T Iterator() where T : class;
    
    public Iterator CreateIterator(IList x) where T : class
    {
            var i = 0; 
            return delegate { return (i < x.Count) ? x[i++] : null; };
    }
    

    So, here is some code that shows how to use the above code...

    var iterator = CreateIterator(new string[3] { "Foo", "Bar", "Baz"});
    
    // So, although CreateIterator() has been called and returned, the variable 
    // "i" within CreateIterator() will live on because of a closure created 
    // within that method, so that every time the anonymous delegate returned 
    // from it is called (by calling iterator()) it's value will increment.
    
    string currentString;    
    currentString = iterator(); // currentString is now "Foo"
    currentString = iterator(); // currentString is now "Bar"
    currentString = iterator(); // currentString is now "Baz"
    currentString = iterator(); // currentString is now null
    

    Hope that is somewhat helpful.

提交回复
热议问题