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> 中的基础集合并导致未定义的行为。

适用于

另请参阅