List<T>.ForEach(Action<T>) 方法
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
对 List<T> 的每个元素执行指定操作。
public:
void ForEach(Action<T> ^ action);
C#
public void ForEach (Action<T> action);
member this.ForEach : Action<'T> -> unit
Public Sub ForEach (action As Action(Of T))
action
为 null
。
已修改集合中的某个元素。
以下示例演示如何使用 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
*/
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) 操作,其中 n 为 Count。
不支持修改委托正文 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 |