What happens with this foreach in C #?

(edit: A little neat code.)

Using foreach like this works great.

var a = new List<Vector2>();

a.ForEach(delegate(Vector2 b) {
    b.Normalize(); });

The following, however, calls "No overload for the ForEach method takes 1 argument."

byte[,,] a = new byte[2, 10, 10];

a.ForEach(delegate(byte b) {
    b = 1; });
+5
source share
6 answers

Raw arrays have far fewer instance methods than general collections, since they are not templates. These methods, such as ForEach()or Sort(), are usually implemented as static methods, which are the templates themselves.

In this case, it will Array.Foreach(a, action)do the trick for the array.

, foreach(var b in a) List, , .

:

  • , .
  • (b=1) . , .
0

ForEach 'es.

Array.ForEach byte[,,] ( ) List.ForEach List<...>.

+2

foreach . , List<T>, .

foreach , - . IEnumerable<T>. .

foreach , . . , IEnumerable ( , , ).

(, ..), LINQ.

, byte, . byte, . :

int[] numbers = new int[] { 1, 2, 3, 4, 5 };

Array.ForEach(numbers, number => number += 1);

foreach(int number in numbers)
{
    Console.WriteLine(number);
}

:

1 2 3 4 5

, + = 1 . , foreach, .

+2

List.ForEach() , Array.ForEach():

public static void ForEach<T>(
    T[] array,
    Action<T> action
)

, , Array.ForEach(). , for

// first dimension
for (int index = 0; index < bytesArray.GetLength(0); index++)             

// second dimension
for (int index = 0; index < bytesArray.GetLength(1); index++)             

// third dimension
for (int index = 0; index < bytesArray.GetLength(2); index++)             
+1

ForEach, . , , .

:

    private static void ForEach<T>(T[, ,] a, Action<T> action)
    {
        foreach (var item in a)
        {
            action(item);
        }
    }

, ForEach:

static class Program
{
    static void Main()
    {
        byte[, ,] a = new byte[2, 10, 10];

        ForEach(a, delegate(byte b)
        {
            Console.WriteLine(b);
        });
    }
    private static void ForEach<T>(T[, ,] a, Action<T> action)
    {
        foreach (var item in a)
        {
            action(item);
        }
    }
}

, ForEach Array , statis. :

Array.ForEach(array, delegate);
+1

List . .

0

All Articles