简体   繁体   English

我们如何使用 `params object[] args` 将可变数量的参数传送到另一种方法?

[英]How do we barrel a variable number of params using `params object[] args` to another method?

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;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM