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

定义

List<T> 的每个元素执行指定操作。Performs the specified action on each element of the 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>

要对 Action<T> 的每个元素执行的 List<T> 委托。The Action<T> delegate to perform on each element of the List<T>.

例外

actionnullaction is null.

已修改集合中的某个元素。An element in the collection has been modified.

示例

下面的示例演示如何使用 Action<T> 委托打印 List<T> 对象的内容。The following example demonstrates the use of the Action<T> delegate to print the contents of a List<T> object. 在此示例中,Print 方法用于将列表的内容显示到控制台。In this example the Print method is used to display the contents of the list to the console.

备注

除了使用 Print 方法显示内容,该C#示例还演示了如何使用匿名方法将结果显示到控制台。In addition to displaying the contents using the Print method, the C# example demonstrates the use of anonymous methods to display the results to the console.

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> 是对传递给它的对象执行操作的方法的委托。The Action<T> is a delegate to a method that performs an action on the object passed to it. 当前 List<T> 的元素分别传递到 Action<T> 委托。The elements of the current List<T> are individually passed to the Action<T> delegate.

此方法的运算复杂度为 O (n),其中nCountThis method is an O(n) operation, where n is Count.

不支持在 Action<T> 委托的正文中修改基础集合,这会导致未定义的行为。Modifying the underlying collection in the body of the Action<T> delegate is not supported and causes undefined behavior.

适用于

另请参阅