|
昨天做程序一下没留神,中了这 C# "Outer Variable Trap" 想了半天才发现错误在哪。 The "Outer Variable Trap" occurs when a developer expects the value of a variable to be captured by a lambda expression or anonymous delegate, when actually the variable is captured itself. Example: var actions = new List<Action>(); for (var i = 0; i < 10; i++) { actions.Add(() => Console.Write("{0} ", i)); } foreach (var action in actions) { action(); } Possible output #1: 0 1 2 3 4 5 6 7 8 9 Possible output #2: 10 10 10 10 10 10 10 10 10 10 If you expected output #1, you've fallen into the Outer Variable Trap. You get output #2. Fix: Declare an "Inner Variable" to be captured repeatedly instead of the "Outer Variable" which is captured only once. var actions = new List<Action>(); for (var i = 0; i < 10; i++) { var j = i; actions.Add(() => Console.Write("{0} ", j)); } foreach (var action in actions) { action(); } |