C# 中 foreach的用法 (補List 的 ForEach細節)


foreach有點像是for的增強版

在C#中有時候會遇到需要循環輸出的情況,比如這樣:

using Syatem
using System.Collections;
using System.Collections.Generic;

class one {
    int[] A = { 1, 2, 3, 4, 5 };
    void Main()
    {
     //for
for (int i = 0; i < A.Length; i++) Console.WriteLine(A[i]);
     //foreach
foreach (int i in A) Console.WriteLine(i); } }

可以看出,當不需要麻煩的操作的時候,不需要針對第 i 元素進行奇怪的操作時,foreach提高了寫代碼的整潔和效率;


注:

1.foreach中的 i 就是A中的元素,如果A是字符串,則應該寫為

foreach (char i in A)
 Console.WriteLine(i);

2.不要在foreach中試圖增刪,這樣會報異常!需使用for!

3.List中有一個ForEach,可以實現在循環內增刪,關於此還有挺多可以說的:

  List中ForEach是有委托的:要對 Action<T> 的每個元素執行的 List<T> 委托

標准寫法: public void ForEach (Action<T> action); ,然后官方給出了一個示例,由此就可以看出用法了:

 1 using System;
 2 using System.Collections.Generic;
 3 
 4 class Program
 5 {
 6     static void Main()
 7     {
 8         List<String> names = new List<String>();
 9         names.Add("Bruce");
10         names.Add("Alfred");
11         names.Add("Tim");
12         names.Add("Richard");
13 
14         // Display the contents of the list using the Print method.
15         names.ForEach(Print);
16 
17         // The following demonstrates the anonymous method feature of C#
18         // to display the contents of the list to the console.
19         names.ForEach(delegate(String name)
20         {
21             Console.WriteLine(name);
22         });
23     }
24 
25     private static void Print(string s)
26     {
27         Console.WriteLine(s);
28     }
29 }
30 /* This code will produce output similar to the following:
31  * Bruce
32  * Alfred
33  * Tim
34  * Richard
35  * Bruce
36  * Alfred
37  * Tim
38  * Richard
39  */
點擊查看全部示范代碼

by the way,此操作是O(n)操作。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM