溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

怎么在C#循環(huán)中捕獲局部變量

發(fā)布時間:2021-09-27 13:33:49 來源:億速云 閱讀:105 作者:小新 欄目:開發(fā)技術

這篇文章主要介紹了怎么在C#循環(huán)中捕獲局部變量,具有一定借鑒價值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。

問題:

我遇到了一個有趣的問題,它的代碼大概是這樣的。

List<Func<int>> actions = new List<Func<int>>();
 
int variable = 0;
while (variable < 5)
{
    actions.Add(() => variable * 2);
    ++ variable;
}
 
foreach (var act in actions)
{
    Console.WriteLine(act.Invoke());
}

 我的期望輸出是 0,2,4,6,8,但它最終輸出的是五個 10,看起來像是這些 action 上下文捕獲的都是同一個變量。

請問是否有變通的方法實現(xiàn)我要的預期結果呢?

解答方案:

變通方法就是在你的 loop 循環(huán)體中使用一個中間變量,并將其送入到 lambda 體中,參考如下代碼:

List<Func<int>> actions = new List<Func<int>>();
 
int variable = 0;
while (variable < 5)
{
    int variable1 = variable;
    actions.Add(() => variable1 * 2);
    ++variable;
}
 
foreach (var act in actions)
{
    Console.WriteLine(act.Invoke());
}
 
Console.ReadLine();

其實這種情況在多線程下也同樣會發(fā)生,比如下面的代碼:

for (int counter = 1; counter <= 5; counter++)
{
    new Thread (() => Console.Write (counter)).Start();
}

 你以為會打印出 1,2,3,4,5,最后的結果非常有趣,在我這里的輸出結果是:2,1,3,3,4 ,你那邊的結果肯定又不一樣了。

唯一的解決方案就是使用 局部變量,修改后的代碼如下:

for (int counter = 1; counter <= 5; counter++)
{
    int localVar= counter;
    new Thread (() => Console.Write (localVar)).Start();
}

總結

可能有很多朋友不知道為什么加了一個 variable1 變量之后,代碼就正確的,要想分析,可以看 C# 生成的 IL 代碼。

private static void Main(string[] args)
{
 List<Func<int>> actions = new List<Func<int>>();
 for (int variable = 0; variable < 5; variable++)
 {
  <>c__DisplayClass0_0 <>c__DisplayClass0_ = new <>c__DisplayClass0_0();
  <>c__DisplayClass0_.variable1 = variable;
  actions.Add(new Func<int>(<>c__DisplayClass0_.<Main>b__0));
 }
 foreach (Func<int> act in actions)
 {
  Console.WriteLine(act());
 }
 Console.ReadLine();
}

 可以清楚的看到,那個所謂的 variable1 成了匿名類 c__DisplayClass0_0 下的字段了,而且foreach循環(huán)中每次都是new的,所以這個字段必然不一樣,這也就保證了正確的結果。

感謝你能夠認真閱讀完這篇文章,希望小編分享的“怎么在C#循環(huán)中捕獲局部變量”這篇文章對大家有幫助,同時也希望大家多多支持億速云,關注億速云行業(yè)資訊頻道,更多相關知識等著你來學習!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

AI