List<T>.ForEach(Action<T>) 方法

定義

List<T> 的每一個項目上執行指定之動作。

public:
 void ForEach(Action<T> ^ action);
public void ForEach (Action<T> action);
member this.ForEach : Action<'T> -> unit
Public Sub ForEach (action As Action(Of T))

參數

action
Action<T>

要在 List<T> 的每一個項目上執行的 Action<T> 委派。

例外狀況

actionnull

集合中的項目已經過修改。

範例

下列範例示範如何使用 Action<T> 委派來列印 物件的內容 List<T> 。 在此範例中, Print 方法用來將清單的內容顯示至主控台。

注意

除了使用 Print 方法顯示內容之外,C# 範例還會示範如何使用 匿名方法 向主控台顯示結果。

List<string> names = new List<string>();
names.Add("Bruce");
names.Add("Alfred");
names.Add("Tim");
names.Add("Richard");

// Display the contents of the list using the Print method.
names.ForEach(Print);

// The following demonstrates the anonymous method feature of C#
// to display the contents of the list to the console.
names.ForEach(delegate(string name)
{
    Console.WriteLine(name);
});

void Print(string s)
{
    Console.WriteLine(s);
}

/* This code will produce output similar to the following:
* Bruce
* Alfred
* Tim
* Richard
* Bruce
* Alfred
* Tim
* Richard
*/
Imports System.Collections.Generic

Class Program
    Shared Sub Main()
        Dim names As New List(Of String)
        names.Add("Bruce")
        names.Add("Alfred")
        names.Add("Tim")
        names.Add("Richard")

        ' Display the contents of the list using the Print method.
        names.ForEach(AddressOf Print)
    End Sub

    Shared Sub Print(ByVal s As String)
        Console.WriteLine(s)
    End Sub
End Class

' This code will produce output similar to the following:
' Bruce
' Alfred
' Tim
' Richard

備註

Action<T>是方法的委派,它會對傳遞給它的物件執行動作。 目前 List<T> 的專案會個別傳遞至 Action<T> 委派。

這個方法是 o (n) 作業,其中 nCount

不支援修改委派主體中的 Action<T> 基礎集合,並導致未定義的行為。

適用於

另請參閱