Question about foreach and delegates

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?

+5
source share
5 answers

UPDATE: there is an extensive analysis and commentary on this:

http://ericlippert.com/2009/11/12/closing-over-the-loop-variable-considered-harmful-part-one/


; , . , , foreach. .

, . #, , "" .

, , , , . , , . !

+11

- , , .

Something, Item. , Item eventargs . , .

" " , .

+5

ItemCollection (generic) List, ForEach -. i:

ItemCollection.ForEach(
    i =>
    {
        Something s = new Something();
        s.EventX += delegate { ProcessItem(i); };
        SomethingCollection.Add(s);
    });

Linq - - :

var somethings = ItemCollection.Select(
        i =>
        {
            Something s = new Something();
            s.EventX += delegate { ProcessItem(i); };
            return s;
        });
foreach(Something s in somethings)
    SomethingCollection.Add(s);
+1

, , , . .

0
foreach(Item i on ItemCollection)
{
   Something s = new Something(i);
   s.EventX += (sender, eventArgs) => { ProcessItem(eventArgs.Item);};
   SomethingCollection.Add(s);
}

"i" "-" EventX event args

0

All Articles