Skip to content

ZH TW 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)

參數集合可從 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學習。

Clone this wiki locally