fMethod
is an Action<Fruit>
.
But when fMethod
is called, the parameter is always the last entry of _Fruits
.
How to solve this?
foreach(Fruit f in _Fruits)
{
field.Add(new Element(f.ToString(),delegate{fMethod(f);}));
}
fMethod
is an Action<Fruit>
.
But when fMethod
is called, the parameter is always the last entry of _Fruits
.
How to solve this?
foreach(Fruit f in _Fruits)
{
field.Add(new Element(f.ToString(),delegate{fMethod(f);}));
}
This is a well-known problem of using a modified clause in a call that creates a delegate. Adding a temporary variable should solve it:
foreach(Fruit f in _Fruits)
{
Fruit tmp = f;
field.Add(new Element(f.ToString(),delegate{fMethod(tmp);}));
}
This problem is fixed in C# 5 (see Eric Lippert's blog).
Try using a temp variable.
foreach(Fruit f in _Fruits)
{
var temp = f;
field.Add(new Element(temp.ToString(),delegate{fMethod(temp);}));
}