可能重複:
C# - The foreach identifier and closures
From Eric Lippert’s blog: 「don’t close over the loop variable」Lambda表達式爲的ThreadStart奇怪的行爲
我使用Lambda表達式作爲ThreadStart
參數,使用運行在一個新線程的方法Thread班。這是我的代碼:
delegate void del();
static void Do(int i)
{
Console.WriteLine(i);
}
static del CreateLoop(del Do)
{
return() =>
{
while (true)
{
Do();
Thread.Sleep(500);
}
};
}
static void Main(string[] args)
{
int n = 0;
var loop = CreateLoop(() => Do(n));
new Thread(() => loop()).Start();
Thread.Sleep(500);
n = 1;
}
這是輸出:
0
1
1
1
...
這怎麼可能?
爲什麼如果我更改我的整數變量n
的值,還會更改i
(Do
的參數)的值?
@ L.B是關於變量範圍,而不是關於捕獲的變量... – gliderkite
gliderkite,所以你遇到一個非常特殊的情況,沒有人面臨過?再次閱讀參考。 –