如何在 C# 中使用参数/param 数组?

csharpprogrammingserver side programming更新于 2025/7/13 4:07:17

声明方法时,您不确定作为参数传递的参数数量。C# param 数组可以帮助您了解这一点。

以下是 param 减号的使用方法

public int AddElements(params int[] arr) {
}

以下是学习如何在 C# 中实现 param 的完整示例 −

示例

using System;

namespace Program {
   class ParamArray {
      public int AddElements(params int[] arr) {
         int sum = 0;

         foreach (int i in arr) {
            sum += i;
         }
         return sum;
      }
   }
   class Demo {
      static void Main(string[] args) {
         ParamArray app = new ParamArray();
         int sum = app.AddElements(300, 250, 350, 600, 120);
   
         Console.WriteLine("The sum is: {0}", sum);
         Console.ReadKey();
      }
   }
}

输出

The sum is: 1620

相关文章