且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将多个可选参数传递给 C# 函数

更新时间:2023-02-22 15:15:23

使用带有 params 修饰符的参数数组:

Use a parameter array with the params modifier:

public static int AddUp(params int[] values)
{
    int sum = 0;
    foreach (int value in values)
    {
        sum += value;
    }
    return sum;
}

如果您想确保至少有 一个 值(而不是可能为空的数组),请单独指定:

If you want to make sure there's at least one value (rather than a possibly empty array) then specify that separately:

public static int AddUp(int firstValue, params int[] values)

(将 sum 设置为 firstValue 以在实现中开始.)

(Set sum to firstValue to start with in the implementation.)

请注意,您还应该以正常方式检查数组引用是否为空.在该方法中,参数是一个非常普通的数组.参数数组修饰符只会在您调用方法时产生影响.基本上编译器会转:

Note that you should also check the array reference for nullity in the normal way. Within the method, the parameter is a perfectly ordinary array. The parameter array modifier only makes a difference when you call the method. Basically the compiler turns:

int x = AddUp(4, 5, 6);

变成类似:

int[] tmp = new int[] { 4, 5, 6 };
int x = AddUp(tmp);

可以用一个完全正常的数组调用它 - 所以后一种语法在源代码中也是有效的.

You can call it with a perfectly normal array though - so the latter syntax is valid in source code as well.