Array.ForEach<T>(T[], Action<T>) Método
Definição
Importante
Algumas informações dizem respeito a um produto pré-lançado que pode ser substancialmente modificado antes de ser lançado. A Microsoft não faz garantias, de forma expressa ou implícita, em relação à informação aqui apresentada.
Executa a ação especificada em cada elemento do array especificado.
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))
Parâmetros de Tipo Genérico
- T
O tipo dos elementos da matriz.
Parâmetros
- array
- T[]
O unidimensional, zero, baseado Array em cujos elementos a ação deve ser realizada.
Exceções
Exemplos
O exemplo seguinte mostra como usar ForEach para mostrar os quadrados de cada elemento num array inteiro.
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
Observações
O Action<T> é um delegado a um método que executa uma ação sobre o objeto que lhe foi passado. Os elementos de array são passados individualmente para o Action<T>.
Este método é uma operação O(n), onde n é o Length de array.
Em F#, a função Array.iter pode ser usada em vez disso.