匿名方法是.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年注冊的,可是博文只寫了幾個,感謝大家的熱情回復!
此題可以結了。請大家看回復之后,如果有補充的地方再回復!