[Visual C#]Params的應用: Method傳入參數同時可以是陣列與Integer?

當我們在撰寫物件導向程式的時候, 難免會需要將參數傳入Method裡面, 若傳入的參數是陣列, 格式如下:

static void Main(string[] args)
{

int[] a = new int[2]{5,7};

Util util = new Util();

Console.WriteLine(util.Min(a));

}

class Util
{

public int Min(int[] param)
{
if (param == null || param.Length == 0)
{
throw new ArgumentException(“Util.Min: not enough arguments”);
}

int currentmin = param[0];

foreach (int i in param)
{
if (i < currentmin)
{
currentmin = i;
}
}

return currentmin;
}

}

這種寫法應該很直觀吧, 但如果傳入的參數是Integer豈不是出現Error? 要怎麼解決呢? 其實要解決這個問題非常簡單, 就是在Method的參數部分加入 “params”這個關鍵字, 寫法如下:

class Util
{

public int Min(params int[] param)
{
if (param == null || param.Length == 0)
{
throw new ArgumentException(“Util.Min: not enough arguments”);
}

int currentmin = param[0];

foreach (int i in param)
{
if (i < currentmin)
{
currentmin = i;
}
}

return currentmin;
}

}

這樣一來傳入的參數會經過compiler做以下的動作:

int min = Util.Min(first, second);
int[] array = new int[2];
array[0] = first;
array[1] = second;
int min = Util.Min(array);

你的主程式就可以彈性傳入參數, 夠方便吧?

static void Main(string[] args)
{

int[] a = new int[2]{5,7};

Util util = new Util();

Console.WriteLine(util.Min(a));//可以傳入陣列型態的變數

int b = util.Min(2, 10); //同時可以傳入多個Integer

Console.WriteLine(b);

}

使用params有幾個注意事項:

  • 陣列不能是multidimensional
  • 使用params的method不能Overloading (多載)
  • 使用params的method不能是ref 或這 out
  • method傳入的參數只能有一個params array
  • 發佈留言

    發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *