Array.ForEach<T>(T[], Action<T>) Methode

Definitie

Voert de opgegeven actie uit op elk element van de opgegeven matrix.

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))

Type parameters

T

Het type van de elementen van de matrix.

Parameters

array
T[]

De eendimensionale nul op basis van Array de elementen waarvan de actie moet worden uitgevoerd.

action
Action<T>

De Action<T> taak die moet worden uitgevoerd op elk element van array.

Uitzonderingen

array is null.

– of –

action is null.

Voorbeelden

In het volgende voorbeeld ziet u hoe ForEach u de kwadraten van elk element in een matrix met gehele getallen kunt weergeven.

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

Opmerkingen

Dit Action<T> is een gemachtigde voor een methode waarmee een actie wordt uitgevoerd op het object dat eraan is doorgegeven. De elementen worden array afzonderlijk doorgegeven aan de Action<T>.

Deze methode is een O(n)-bewerking, waarbij n de Length van array.

In F# kan de functie Array.iter worden gebruikt.

Van toepassing op

Zie ook