c# - How does linq lambdas work inside a loop? -


I am trying to implement the work in my application.

Here is the sample code:

There is a simple interface I have, 3 sections form (A, B, C) I have it a list of poplualte with A, B, C examples Are making, and then call to do another function method for each other do1 ();

  Interface I {void do1 (); } Class A: I {Public Zero do1 () {Console.WriteLine ("A"); }} Class B: I {Public Zero do1 () {Console.WriteLine ("B"); }} Category C: I {public void do1 () {Console.WriteLine ("C"); }} Class program {public static zero main (string [] args {list & lt; I & gt; L = new list & lt; I & gt; (); L. Add (new A ()); L. Add (New B) L. Add (new C ()); Var workpool = new list & lt; Work & gt; (); Foreach (in var i) {Task Task = New Function (() = & gt; i.do1 ()); TaskPool.Add (work); } Foreach (Taskball in Work C) {c.Start (); } Thread. Sleep (3000); Console.Read (); }}  

I hope to see

  ABC  

In output, but instead I have some There was a problem in the debugger: all the functions were the same representative, but I do not know how this and how it works for the reason. "Gtc: suffix =" "gtc: mediawiki-xid =

This is a very common question How "Captured Character" is related to the work; Short version, you need it:

(code) fore work (var i in l) {var copy = i; task work = new task ( } => Copy.do1 (); TaskPool.Add (function);}

The problem here is that i ( foreach < technically declared outside the scope of the loop , and thus the external radius is captured; every time Capture the same variable (C # capture variable , not * value). copy in the loop area < Adding / em> this changes; Due to the scope, copy has been seperated per recursive .


Comments