【转】.NET 匿名方法的BUG,请专家解答
匿名方法是.NET 3.5之后的一个好东东,很多人使用,但是我在最近的工作当中发现了一个问题. 请专家解答
1 //list里存放10个数字 2 List<int> list = new List<int>(10); 3 for (int i = 0; i < 10; i++) 4 { 5 list.Add(i); 6 } 7 8 //10个数字,分成10组,其实每组就一个元素,每组的元素是不相同的 9 Dictionary<int, List<int>> dict = new Dictionary<int, List<int>>(); 10 for (int i = 0; i < 10; i++) 11 { 12 int k = i % 10; 13 if (dict.ContainsKey(k)) 14 { 15 dict[k].Add(i); 16 } 17 else 18 { 19 dict[k] = new List<int>(); 20 dict[k].Add(i); 21 } 22 }
接下来,我们先采用非匿名方法,实现打印每个组里的元素,代码如下
1 using (Dictionary<int, List<int>>.Enumerator enumerator = dict.GetEnumerator()) 2 { 3 KeyValuePair<int, List<int>> keyValue; 4 while (enumerator.MoveNext()) 5 { 6 keyValue = enumerator.Current; 7 8 System.Threading.Thread thread = new System.Threading.Thread(Display); 9 thread.Start(keyValue.Value); 10 } 11 } 12 13 public static void Display(object o) 14 { 15 List<int> list = o as List<int>; 16 foreach (var item in list) 17 { 18 Console.WriteLine(item.ToString()); 19 } 20 }
输出的结果是:
0
1
2
3
4
5
6
7
8
9
没有问题!!! 一切OK
好,我们换一种方式为实现输出各组的元素,采用匿名委托的方式.
1 using (Dictionary<int, List<int>>.Enumerator enumerator = dict.GetEnumerator()) 2 { 3 KeyValuePair<int, List<int>> keyValue; 4 while (enumerator.MoveNext()) 5 { 6 keyValue = enumerator.Current; 7 System.Threading.Thread thread = new System.Threading.Thread(delegate() 8 { 9 foreach (var item in keyValue.Value) 10 { 11 Console.WriteLine(item.ToString()); 12 } 13 } 14 ); 15 thread.Start(); 16 } 17 }
采用上面的代码,输出的结果不定,而且会出现重复的数据,结果可能如下
3
3
3
4
4
4
5
5
7
9
请专家解答一下,我一直没有找到原因!
这个号是09年注册的,可是博文只写了几个,感谢大家的热情回复!
此题可以结了。请大家看回复之后,如果有补充的地方再回复!
==================================原文链接===此文章由博客转发小工具转发==================================
- 学习本是一个不断抄袭、模仿、练习、创新的过程。
- 虽然,园中已有本人无法超越的同主题博文,为什么还是要写。
- 对于自己,博文只是总结。在总结的过程发现问题,解决问题。
- 对于他人,在此过程如果还能附带帮助他人,那就再好不过了。
- 由于博主能力有限,文中可能存在描述不正确,欢迎指正、补充!
- 感谢您的阅读。如果文章对您有用,那么请轻轻点个赞,以资鼓励。
- 工控物联Q群:995475200