What was the constructive solution for variational functions requiring an array?

I'm curious and hopefully someone can shed a bit on this, but why should C # functions that accept "params" have to be an array?

I get that the objects in the parameter list are entered into the array, but what if someone wants to create a variational function that takes an undefined number of array objects?

Take this function, for example ...

private Int32 Sum(params Int32[] numbers)
{
    return numbers.Sum(); // Using LINQ here to sum
}

Pretty straight forward, it can take a different number of numbers - for example ...

Int32 x = Sum(1);
Int32 y = Sum(1, 2);
Int32 z = Sum(1, 2, 3);

Now let's say that I want to create a function that takes a different number of Integer arrays and sums all the numbers. As far as I know, I will have to consider boxing ...

private Int32 SumArrays(params Object[] numbers)
{
    Int32 total = 0;
    foreach (Object o in numbers)
    {
        Int32[] array = (Int32[])o;

        total += array.Sum();
    }
    return total;
}

What could be used as ...

Int32[] arr1 = new Int32[] { 1, 2, 3 };
Int32[] arr2 = new Int32[] { 1, 2, 3, 4 };
Int32[] arr3 = new Int32[] { 1, 2, 3, 4, 5 };

Int32 x = SumArrays((Object)arr1, (Object)arr2);
Int32 y = SumArrays((Object)arr1, (Object)arr2, (Object)arr3);

? ? , params Int32?

+3
2

, :

private int SumAll(params int[][] args)
{
    int result = 0;
    for (int x = 0; x < args.Length; x++)
    {
        for (int y = 0; y < args[x].Length; y++)
        {
            result += args[x][y];
        }
    }
    return result;
}

.

+3

, , , . , int, ​​ int.

static int SumArrays(params int[][] data)
{
    int rval = 0;
    for (int i = 0; i < data.Length; i++)
    {
        rval += data[i].Sum();
    }
    return rval;
}
0

Source: https://habr.com/ru/post/1712585/


All Articles