Resharperは、次のコードについて不平を言っています。
foreach (string data in _dataList)
DoStuff (() => field);
クロージャとは何ですか?そして、なぜ私は気にする必要がありますか?
数学と関数型プログラミングのクロージャーについて読んだのですが、ここで途方に暮れています。私の脳には重すぎる。
簡単に言えば、ここで何が起こっているのでしょうか。
Resharperは、次のコードについて不平を言っています。
foreach (string data in _dataList)
DoStuff (() => field);
クロージャとは何ですか?そして、なぜ私は気にする必要がありますか?
数学と関数型プログラミングのクロージャーについて読んだのですが、ここで途方に暮れています。私の脳には重すぎる。
簡単に言えば、ここで何が起こっているのでしょうか。
Here is a fairly good explanation.
A closure is created when you reference a variable in the body of a method from a delegate. Essentially, a class that contains a reference to the local variable is generated.
If the variable is constantly modified, when an external method calls the delegate, it may contain an unpredictable value, or even throw an exception.
For example, in an example like this:
foreach (string data in _dataList)
{
DoStuff (() => data);
}
The method () => data
is always going to be the same method. if you store it, you don't know what happens when it's eventually invoked -- what will the value of data
be at the time? Will it even be valid? This is especially dangerous if you use yield return
.
A simpler example, without an iterator, is:
var x = 5;
Action f = () => Console.WriteLine(x);
x = 76;
f();