Skip to content

JA CSharp Keyword params

Codex edited this page Oct 11, 2026 · 2 revisions

Українська · Русский · English · Deutsch · Français · Italiano · Español · 繁體中文 · 日本語 · 한국어

C#: params

ディレクトリ C# · 実践的な指導

異なる数の引数を使用して呼び出しを許可します。配列またはサポートされているコレクション形式を渡します。メソッドの最後のパラメータです。

簡単な例 (Example.cs)

この例を Example.cs として別に保存し、このページの他の例とは独立して実行してください。

Example.cs:

// PROJECT-EXAMPLE
int Sum(params int[] values)
{
    int total = 0;
    foreach (int value in values) total += value;
    return total;
}
System.Console.WriteLine(Sum(1, 2, 3));

結果:

6

構文

Method(params int[] values) / Method(params ReadOnlySpan<int> values)

params コレクションは C# 13 から入手できます。大規模な形式は言語の以前のバージョンに存在します。

例 1: 基本形式

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;

public static class Program
{
    public static async Task Main(string[] args)
    {
        Console.WriteLine(Numbers.Sum(1, 2, 3));
        Console.WriteLine(Numbers.Sum(new int[] { 4, 5 }));
    }
}
public static class Numbers { public static int Sum(params int[] values) => values.Sum(); }

例 2: 別の実用的な形式

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;

public static class Program
{
    public static async Task Main(string[] args)
    {
        Console.WriteLine(Numbers.Sum(2, 4, 6));
    }
}
public static class Numbers { public static int Sum(params ReadOnlySpan<int> values) { int sum = 0; foreach (int value in values) sum += value; return sum; } }

公式ソース: Microsoft Learn。

Clone this wiki locally