param數組允許我們只寫一個方法, 就能接受數量可變的參數. 這種技術就是參數數組,它本質上是用params關鍵字來聲明的一個參數.而且不僅可以聲明params int[] list這樣的數組,還可以聲明object類型的參數組,參數可以是任意類型的~
Util類
- #region Using directives
- using System;
- #endregion
- namespace ParamsArray
- {
- class Util
- {
- public static int Sum(params int[] paramList)
- {
- if (paramList == null)
- {
- throw new ArgumentException("Util.Sum: null parameter list");
- }
- if (paramList.Length == 0)
- {
- throw new ArgumentException("Util.Sum: empty parameter list");
- }
- int sumTotal = 0;
- foreach (int i in paramList)
- {
- sumTotal += i;
- }
- return sumTotal;
- }
- public static void Everyone(params object[] paramobject)
- {
- if (paramobject == null)
- {
- throw new Exception("Util.Everyone: null parameter list");
- }
- if (paramobject.Length == 0)
- {
- throw new Exception("Util.Everyone: empty parameter list");
- }
- foreach (object i in paramobject)
- {
- Console.WriteLine(i);
- }
- }
- }
- }
Program類
- #region Using directives
- using System;
- using System.Collections.Generic;
- using System.Text;
- #endregion
- namespace ParamsArray
- {
- class Program
- {
- static void Entrance()
- {
- Console.WriteLine(Util.Sum(10, 9, 8, 7, 6, 5, 4, 3, 2, 1));
- }
- static void Entrance01()
- {
- Console.WriteLine(Util.Sum()); //長度爲0
- }
- static void Entrance02()
- {
- Console.WriteLine(Util.Sum(null)); //數組爲null
- }
- static void Entrance03()
- {
- Util.Everyone("dkjf", 45, "654", 451.5);
- }
- static void Main()
- {
- try
- {
- Entrance();
- Entrance01();
- }
- catch (Exception ex)
- {
- Console.WriteLine("Exception: {0}", ex.Message);
- }
- try
- {
- Entrance02();
- }
- catch (Exception ex)
- {
- Console.WriteLine("Exception: {0}", ex.Message);
- }
- try
- {
- Entrance03();
- }
- catch (System.Exception ex)
- {
- Console.WriteLine("Exception: {0}", ex.Message);
- }
- }
- }
- }
每個try語句執行後,try語句內部的在Exception之後的部分就不會再執行了,所以要另外再寫一個try語句。
語句的執行效果如下: