c#中不定长参数(关键字Params)使用

Params:params 关键字可以指定在参数数目可变处采用参数的方法参数。

注意点:

1、一个方法中只能使用一个params来声明不定长参数数组;

2、params参数数组只能放在已定义参数后面

3、在方法声明中的 params 关键字之后不允许任何其他参数

示例代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ParamsUse
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(Sum(2, 4, 6, 8, 10));
            ListParams("江西省", "宜春市", "高安市");
            Console.ReadKey();
        }
        public static int Sum(params int[] intparams)
        {
            int sum = 0;
            for (int i = 0; i < intparams.Length; i++)
            {
                sum += intparams[i];
            }
            return sum;
        }
        static void ListParams(params string[] strs)
        {
            foreach (var item in strs)
            {
                Console.WriteLine(item);
            }
        }
    }
}