「C#」paramsで可変長な引数を定義するサンプル

書式
関数名(params 型[] 変数名)
paramsと共に、可変長にしたい型を配列で定義します。
paramsキーワードを使用して可変長な引数を定義します。
使い方
関数名(引数1,引数2…)

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
using System;
namespace Sample
{
class Sample
{
static void Main()
{
int resA = funSum(2, 4, 5);
Console.WriteLine("可変長引数3つ結果1: "+resA);
int resB = funSum(4, 5);
Console.WriteLine("可変長引数2つ結果2: "+resB);
Console.ReadKey();
}
//可変長引数を持つ関数の定義
public static int funSum(params int[] nums)
{
int sum = 0;
foreach (int x in nums)
{
sum = sum + x;
}
return sum;
}
}
}
using System; namespace Sample { class Sample { static void Main() { int resA = funSum(2, 4, 5); Console.WriteLine("可変長引数3つ結果1: "+resA); int resB = funSum(4, 5); Console.WriteLine("可変長引数2つ結果2: "+resB); Console.ReadKey(); } //可変長引数を持つ関数の定義 public static int funSum(params int[] nums) { int sum = 0; foreach (int x in nums) { sum = sum + x; } return sum; } } }
using System;
 
namespace Sample
{
    class Sample
    {
        static void Main()
        {
             int resA = funSum(2, 4, 5);
             Console.WriteLine("可変長引数3つ結果1: "+resA);
             
             int resB = funSum(4, 5);
             Console.WriteLine("可変長引数2つ結果2: "+resB);
            
             Console.ReadKey();
        }
        //可変長引数を持つ関数の定義
        public static int funSum(params int[] nums)
        {
            int sum = 0;
            foreach (int x in nums)
             {
               sum = sum + x;
              }
            return sum;
          }
    }
}

実行結果
可変長引数3つ結果1: 11
可変長引数2つ結果2: 9

C#

Posted by arkgame