问题:
我遇到了一个有趣的问题,它的代码大概是这样的。
1
2
3
4
5
6
7
8
9
10
11
12
13
|
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 上下文捕获的都是同一个变量。
请问是否有变通的方法实现我要的预期结果呢?
解答方案:
变通方法就是在你的 loop 循环体中使用一个中间变量,并将其送入到 lambda 体中,参考如下代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
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(); |
其实这种情况在多线程下也同样会发生,比如下面的代码:
1
2
3
4
|
for ( int counter = 1; counter <= 5; counter++) { new Thread (() => Console.Write (counter)).Start(); } |
你以为会打印出 1,2,3,4,5,最后的结果非常有趣,在我这里的输出结果是:2,1,3,3,4 ,你那边的结果肯定又不一样了。
唯一的解决方案就是使用 局部变量,修改后的代码如下:
1
2
3
4
5
|
for ( int counter = 1; counter <= 5; counter++) { int localVar= counter; new Thread (() => Console.Write (localVar)).Start(); } |
总结
可能有很多朋友不知道为什么加了一个 variable1 变量之后,代码就正确的,要想分析,可以看 C# 生成的 IL 代码。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
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循环中每次都是new的,所以这个字段必然不一样,这也就保证了正确的结果。
到此这篇关于如何在C#循环中捕获局部变量的文章就介绍到这了,更多相关C#循环捕获局部变量内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://blog.csdn.net/qq_41872328/article/details/120301266