Assume the following code:
foreach(Item i on ItemCollection)
{
Something s = new Something();
s.EventX += delegate { ProcessItem(i); };
SomethingCollection.Add(s);
}
Of course, this is wrong, because all delegates point to the same Subject. Alternative:
foreach(Item i on ItemCollection)
{
Item tmpItem = i;
Something s = new Something();
s.EventX += delegate { ProcessItem(tmpItem); };
SomethingCollection.Add(s);
}
In this case, all delegates point to their own element.
How about this approach? Is there any other better solution?
source
share