C# params 关键字详解

params 关键字用于声明参数数组 ,允许方法接受可变数量的参数 。它是创建可变参数方法的便捷方式。

基本语法

复制代码
// params 参数必须是方法最后一个参数
public void Method(params int[] numbers)
{
    // numbers 是一个 int 数组
}

// 调用时可以传递任意数量的参数
Method(1, 2, 3, 4, 5);
Method(10, 20);
Method();  // 也可以不传递参数

使用示例

1. 基础用法

复制代码
public int Sum(params int[] numbers)
{
    int total = 0;
    foreach (int num in numbers)
    {
        total += num;
    }
    return total;
}

// 调用
int result1 = Sum(1, 2, 3);           // 6
int result2 = Sum(10, 20, 30, 40);    // 100
int result3 = Sum();                  // 0

2. 与其他参数结合

复制代码
// params 必须是最后一个参数
public string Format(string format, params object[] args)
{
    return string.Format(format, args);
}

// 调用
string result = Format("姓名:{0},年龄:{1},成绩:{2}", "张三", 20, 95.5);

3. 传递数组

复制代码
// 可以直接传递数组
public void Process(params string[] items)
{
    foreach (var item in items)
    {
        Console.WriteLine(item);
    }
}

// 调用方式1:传递多个参数
Process("A", "B", "C");

// 调用方式2:传递数组
string[] array = { "X", "Y", "Z" };
Process(array);  // 会自动识别为 params 参数

// 调用方式3:空参数
Process();  // 传递空数组
相关推荐
Wenweno0o1 天前
0基础Go语言Eino框架智能体实战-chatModel
开发语言·后端·golang
chenjingming6661 天前
jmeter线程组设置以及串行和并行设置
java·开发语言·jmeter
cch89181 天前
Python主流框架全解析
开发语言·python
不爱吃炸鸡柳1 天前
C++ STL list 超详细解析:从接口使用到模拟实现
开发语言·c++·list
十五年专注C++开发1 天前
RTTR: 一款MIT 协议开源的 C++ 运行时反射库
开发语言·c++·反射
Momentary_SixthSense1 天前
设计模式之工厂模式
java·开发语言·设计模式
‎ദ്ദിᵔ.˛.ᵔ₎1 天前
STL 栈 队列
开发语言·c++
勿忘,瞬间1 天前
数据结构—顺序表
java·开发语言
张張4081 天前
(域格)环境搭建和编译
c语言·开发语言·python·ai
weixin_423533991 天前
【Windows11离线安装anaconda、python、vscode】
开发语言·vscode·python