C #, Pass Array as functional parameters

In python *, it allows me to pass a list as parameters to a function:

def add(a,b): return a+b
x = [1,2]
add(*x)

Can I reproduce this behavior in C # with an array?

Thanks.

+5
source share
4 answers

With the exception of:

  • Change the method signature for accepting an array
  • Adding overload, which takes an array, retrieves the values ​​and causes the original overload
  • Using reflection to call a method

then unfortunately no, you cannot do this.

Keyword-based and positioning-based parameter passing, like in Python, is not supported in .NET, except for reflection.

, , , , , , , " ?". , , , .NET , , , - , , , .

, , , , , , .NET , .

:

using System;
using System.Reflection;

namespace ConsoleApplication1
{
    class Program
    {
        public Int32 Add(Int32 a, Int32 b) { return a + b; }
        static void Main(string[] args)
        {
            Program obj = new Program();

            MethodInfo m = obj.GetType().GetMethod("Add");
            Int32 result = (Int32)m.Invoke(obj, new Object[] { 1, 2 });
        }
    }
}
+9

params

public int Add(params int[] numbers) {
    int result = 0;

    foreach (int i in numbers) {
        result += i;
    }

    return result;
}

// to call:
int result = Add(1, 2, 3, 4);
// you can also use an array directly
int result = Add(new int[] { 1, 2, 3, 4});
+12

. , , , , , / .

+2
source

I'm sure you can use reflection to access your method, and then use Invoke , using your array as a parameter to the list. However, the view is around.

+1
source

All Articles