C# - 引數陣列



有時,在宣告方法時,你不確定作為引數傳遞的引數數量。C# 引數陣列(或引數陣列)這時可以派上用場。

以下示例對此進行了演示 -

using System;

namespace ArrayApplication {
   class ParamArray {
      public int AddElements(params int[] arr) {
         int sum = 0;
         
         foreach (int i in arr) {
            sum += i;
         }
         return sum;
      }
   }
   class TestClass {
      static void Main(string[] args) {
         ParamArray app = new ParamArray();
         int sum = app.AddElements(512, 720, 250, 567, 889);
         
         Console.WriteLine("The sum is: {0}", sum);
         Console.ReadKey();
      }
   }
}

當上面程式碼編譯並執行時,會產生以下結果 -

The sum is: 2938
csharp_arrays.htm
廣告