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 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 函式。