我目前正在尋找棘手的采訪片段,我發現了兩個我無法解釋的片段。我將它們合并在一起,以便它們可以同時運行。
這是代碼:
using System.Collections.Generic;
public class Program
{
public static void Main(string[] args)
{
var intActions = new List<Action>();
for (int i = 0; i < 4; i )
intActions.Add(() => { Console.WriteLine(i); });
foreach (var action in intActions)
action();
string[] strings = { "abc", "def", "ghi" };
var stringActions = new List<Action>();
foreach (string str in strings)
stringActions.Add(() => { Console.WriteLine(str); });
foreach (var action in stringActions)
action();
}
}
輸出是:
4
4
4
4
abc
def
ghi
誰能解釋我為什么會出現這樣的結果?我希望四個“4”帶有四個“ghi”或“0123”和“abc def ghi”
uj5u.com熱心網友回復:
您看到4444而不是0123&ghi ghi ghi而不是的abc def ghi原因是由于關閉。
傳遞給委托的i變數是通過參考而不是值傳遞的,這意味著所有操作都將指向變數i和最新值的相同記憶體位置i(在回圈的最后一次迭代中設定為 4)。
對于輸出為0123,將變數復制到另一個臨時變數將意味著每個操作都有一個指向單獨記憶體位置的指標,因此產生“預期”的數字。
var intActions = new List<Action>();
for (int i = 0; i < 4; i ) {
int copy = i;
intActions.Add(() => { Console.WriteLine(copy); });
}
foreach (var action in intActions)
action();
相同的概念適用于示例的第二部分:
string[] strings = { "abc", "def", "ghi" };
var stringActions = new List<Action>();
foreach (string str in strings) {
var copy = str;
stringActions.Add(() => { Console.WriteLine(copy); });
}
foreach (var action in stringActions)
action();
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/457634.html
上一篇:使用LINQ在串列中鏈接對
