Array.ForEach<T>(T[], Action<T>) 메서드

정의

지정한 배열의 각 요소에서 지정한 동작을 수행합니다.

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[]

해당 요소에서 동작이 수행되는 1차원 Array (인덱스는 0부터 시작)입니다.

action
Action<T>

array의 각 요소에서 수행할 Action<T>입니다.

예외

array이(가) null인 경우

또는

action이(가) null인 경우

예제

다음 예제에서는 를 사용하여 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 는 의 array입니다Length.

F#에서는 Array.iter 함수를 대신 사용할 수 있습니다.

적용 대상

추가 정보