Is it still closing?

The testit () method is a closure. aString is out of scope, but testit () can still execute on it anyway. testit2 () uses a variable that did not fall out of scope (mystring), but which was also not passed to testit2 (). Is testit2 () considered closure?

string mystring = "hello world";
Action testit = new Action(delegate { string aString = "in anon method"; Debug.WriteLine(aString); });
testit();

//capture mystring.  Is this still a closure?
Action testit2 = new Action(delegate { Debug.WriteLine(mystring); });
//mystring is still in scope
testit2();

In the second example, mystring can be updated outside the method, and these changes will be reflected in testit2 (). This does not behave like a normal method that could only capture mystring as a parameter.

+3
source share
3 answers

- . . . , .

, . .

, . , , .

+6

, . , , , .

+3

testit- this is not so much a closure as testit2it is only the use of a locally defined variable, and not one in the "parent" environment (for example, mystring).

However, I would say that both are closures, as they have the ability to capture variables from the environment due to anonymous methods.

+1
source

Source: https://habr.com/ru/post/1703305/


All Articles