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




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章