![](/img/trans.png)
[英]Why does invoking a method with params object[] as args throw a cast error?
[英]How do we barrel a variable number of params using `params object[] args` to another method?
官方文檔頁面中沒有示例。
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;
}
}
你可以簡單地做如下
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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.