某委員会
企画調整委員会で出たコメントを精査し,最終的な修正を決定.さて,ここで話題になった(また私が発散させてしまった…)のがdelegateの挙動.14.5.15.3.2に次のような記述がある.
Ordinarily, there is no way to observe exactly how often a local variable is instantiated--because the lifetimes of the instantiations are disjoint, it is possible for each instantiation to simply use the same storage location. However, when an anonymous method captures a local variable, the effects of instantiation become apparent.
つまり,次のようなプログラムにおける"x"は,いかにも局所変数のように見えるのだが,実際にはdelegateを使うことで変数の生存期間が重なってしまうことになる.
using System; class Test { static D[] F() { D[] result = new D[3]; for (int i = 0; i < 3; i++) { int x = i * 2 + 1; result[i] = delegate { Console.writeLine(x); }; } return result; } static void Main() { foreach (D d in F()) d(); } }