No example from the official docs page .
public class MyClass
{
public static void Foo(params int[] args)
{
Bar(args) // error (I want to automatically pass args e.g.: Bar(args[0], args[1], args[2]...))
}
public static int Bar(int a, int b, int c, int d, int e) {
return a + b + c + d + e;
}
}
You can simply do like below
public static void Foo(params int[] args)
{
Bar(args); // error (I want to automatically pass args e.g.: Bar(args[0], args[1], args[2]...))
}
public static int Bar(params int [] values)
{
int total = 0;
foreach (int value in values)
{
total += value;
}
return total;
//return a + b + c + d + e;
}
using System;
using System.Linq;
using System.Reflection;
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Foo(1, 2, 3, 4, 5)); //outputs 15
}
public static int Foo(params int[] args)
{
return (int)typeof(Program).GetMethod(nameof(Bar), BindingFlags.Public | BindingFlags.Static).Invoke(null, args.Select(v => (object)v).ToArray());
}
public static int Bar(int a, int b, int c, int d, int e)
{
return a + b + c + d + e;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.