无涯教程-C# - 参数函数

61 阅读1分钟

有时,在声明方法时,您不确定参数的数量,C# param参数数组在这种情况下会得到帮助。

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

参考链接

www.learnfk.com/csharp/csha…