Array.ForEach<T>(T[], Action<T>) 方法
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
对指定数组的每个元素执行指定操作。
public:
generic <typename T>
static void ForEach(cli::array <T> ^ array, Action<T> ^ action);
public static void ForEach<T> (T[] array, Action<T> action);
static member ForEach : 'T[] * Action<'T> -> unit
Public Shared Sub ForEach(Of T) (array As T(), action As Action(Of T))
类型参数
- T
数组元素的类型。
参数
- array
- T[]
从零开始的一维 Array,要对其元素执行操作。
例外
示例
以下示例演示如何使用 ForEach 显示整数数组中每个元素的平方。
using namespace System;
public ref class SamplesArray
{
public:
static void Main()
{
// create a three element array of integers
array<int>^ intArray = gcnew array<int> {2, 3, 4};
// set a delegate for the ShowSquares method
Action<int>^ action = gcnew Action<int>(ShowSquares);
Array::ForEach(intArray, action);
}
private:
static void ShowSquares(int val)
{
Console::WriteLine("{0:d} squared = {1:d}", val, val*val);
}
};
int main()
{
SamplesArray::Main();
}
/*
This code produces the following output:
2 squared = 4
3 squared = 9
4 squared = 16
*/
using System;
public class SamplesArray
{
public static void Main()
{
// create a three element array of integers
int[] intArray = new int[] {2, 3, 4};
// set a delegate for the ShowSquares method
Action<int> action = new Action<int>(ShowSquares);
Array.ForEach(intArray, action);
}
private static void ShowSquares(int val)
{
Console.WriteLine("{0:d} squared = {1:d}", val, val*val);
}
}
/*
This code produces the following output:
2 squared = 4
3 squared = 9
4 squared = 16
*/
open System
let showSquares val' =
printfn $"%i{val'} squared = %i{val' * val'}"
// create a three element array of integers
let intArray = [| 2..4 |]
Array.ForEach(intArray, showSquares)
// Array.iter showSquares intArray
// This code produces the following output:
// 2 squared = 4
// 3 squared = 9
// 4 squared = 16
Public Class SamplesArray
Public Shared Sub Main()
' create a three element array of integers
Dim intArray() As Integer = New Integer() {2, 3, 4}
' set a delegate for the ShowSquares method
Dim action As New Action(Of Integer)(AddressOf ShowSquares)
Array.ForEach(intArray, action)
End Sub
Private Shared Sub ShowSquares(val As Integer)
Console.WriteLine("{0:d} squared = {1:d}", val, val*val)
End Sub
End Class
' This code produces the following output:
'
' 2 squared = 4
' 3 squared = 9
' 4 squared = 16
注解
Action<T>是方法的委托,该方法对传递给它的 对象执行操作。 的 array
元素单独传递给 Action<T>。
此方法是 O (n
) 操作,其中 n
是 Length 的 array
。
在 F# 中,可以改用 Array.iter 函数。