Array.ForEach<T>(T[], Action<T>) Metod
Definition
Viktigt
En del information gäller för förhandsversionen av en produkt och kan komma att ändras avsevärt innan produkten blir allmänt tillgänglig. Microsoft lämnar inga garantier, uttryckliga eller underförstådda, avseende informationen som visas här.
Utför den angivna åtgärden för varje element i den angivna matrisen.
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))
Typparametrar
- T
Typ av element i matrisen.
Parametrar
- array
- T[]
Den endimensionella noll baserat Array på vars element åtgärden ska utföras.
Undantag
Exempel
I följande exempel visas hur du använder ForEach för att visa kvadraterna för varje element i en heltalsmatris.
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
Kommentarer
Action<T> är ett ombud till en metod som utför en åtgärd på objektet som skickas till den. Elementen array i skickas individuellt till Action<T>.
Den här metoden är en O()-nåtgärd, där n är för Lengtharray.
I F#kan funktionen Array.iter användas i stället.