C # Action in Foreach

fMethodis Action<Fruit>.

But when called fMethod, the parameter is always the last record _Fruits.
How to solve this?

foreach(Fruit f in _Fruits)
{
   field.Add(new Element(f.ToString(),delegate{fMethod(f);}));
}
+5
source share
2 answers

This is a well-known problem using a modified sentence in a call that a delegate creates. Adding a temporary variable should solve this problem:

foreach(Fruit f in _Fruits)
{
    Fruit tmp = f;
    field.Add(new Element(f.ToString(),delegate{fMethod(tmp);}));
}

This issue has been fixed in C # 5 ( see Eric Lippert's blog ).

+9
source

Try using a temporary variable.

foreach(Fruit f in _Fruits)
{
   var temp = f;
   field.Add(new Element(temp.ToString(),delegate{fMethod(temp);}));
}
+1
source

All Articles