數組的長度是不可變的,但是通過params修飾符可以模擬出數組長度可變的效果。
namespace params參數
{
class Program
{
static void Main(string[] args)
{
fun(1,100,100,100); //等效於下面的操作
/*
int ID = 1;
int[] score = {100,100,100 };
fun(ID,score);
*/
Console.ReadKey();
}
public static void fun(int ID,params int[] score)//params修飾的可變數組作爲形參一定要放在最後,避免和前面的int類型混淆
{
int sum = 0;
for (int i = 0; i < score.Length;i++)
{
sum += score[i];
}
Console.WriteLine("ID={0},sum={1}",ID,sum);
}
}
}