fMethod
はAction<Fruit>
です。ForeachのC#アクション
しかし、fMethod
が呼び出されたとき、パラメータは常に_Fruits
の最後のエントリです。
これを解決するにはどうすればよいですか?
foreach(Fruit f in _Fruits)
{
field.Add(new Element(f.ToString(),delegate{fMethod(f);}));
}
fMethod
はAction<Fruit>
です。ForeachのC#アクション
しかし、fMethod
が呼び出されたとき、パラメータは常に_Fruits
の最後のエントリです。
これを解決するにはどうすればよいですか?
foreach(Fruit f in _Fruits)
{
field.Add(new Element(f.ToString(),delegate{fMethod(f);}));
}
これは、代理人を作成する呼び出しで変更された句を使用するよく知られた問題です。一時変数を追加すると、それを解決する必要があります。
foreach(Fruit f in _Fruits)
{
Fruit tmp = f;
field.Add(new Element(f.ToString(),delegate{fMethod(tmp);}));
}
この問題は、C#5(see Eric Lippert's blog)に固定されています。
この問題は** C#5.0で修正されています** http://blogs.msdn.com/b/ericlippert/archive/2009/11/12/closing -over-the-loop-variable-considered-harmful.aspx –
@DasKrümelmonsterそれは非常に知っていいです、ありがとう! – dasblinkenlight
一時変数を使用してください。
foreach(Fruit f in _Fruits)
{
var temp = f;
field.Add(new Element(temp.ToString(),delegate{fMethod(temp);}));
}
の可能性の重複が[foreachの中の変数のC#の再利用のための理由はありますか?](http://stackoverflow.com/questions/8898925/is-there-a-reason-for-cs- foreachでの再利用) – Joey