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

定义

List<T> 的每个元素执行指定操作。

C#
public void ForEach (Action<T> action);

参数

action
Action<T>

要对 List<T> 的每个元素执行的 Action<T> 委托。

例外

actionnull

已修改集合中的某个元素。

示例

以下示例演示如何使用 Action<T> 委托来打印 对象的内容 List<T> 。 在此示例中, Print 方法用于向控制台显示列表的内容。

备注

除了使用 Print 方法显示内容外,C# 示例还演示了如何使用 匿名方法 向控制台显示结果。

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
*/

注解

Action<T>是方法的委托,该方法对传递给它的 对象执行操作。 当前 List<T> 元素单独传递给 Action<T> 委托。

此方法是 O (n) 操作,其中 nCount

不支持修改委托正文 Action<T> 中的基础集合,这会导致未定义的行为。

适用于

产品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

另请参阅