C# 方法中的参数数组

发布时间 2024-01-12 14:51:49作者: 清和时光

前言:
有时候我们不能精确的确定一个方法需要多少个参数,
C#中有一个叫参数数组,就是把数组作为方法的参数,使用 params 关键字标记的参数必须为数组类型,并且必须是该方法的参数列表中的最后一个参数。
然后,调用方可通过以下四种方式中的任一种来调用方法:

传递相应类型的数组,该类型包含所需数量的元素。
向该方法传递相应类型的单独自变量的逗号分隔列表。
传递 null。
不向参数数组提供参数。

以下示例定义了一个名为 GetVowels 的方法,该方法返回参数数组中的所有元音。 Main 方法演示了调用方法的全部四种方式。 调用方不需要为包含 params 修饰符的形参提供任何实参。 在这种情况下,参数是一个空数组。

static class ParamsExample
{
    static void Main()
    {
        string fromArray = GetVowels(["apple", "banana", "pear"]);
        Console.WriteLine($"Vowels from array: '{fromArray}'");

        string fromMultipleArguments = GetVowels("apple", "banana", "pear");
        Console.WriteLine($"Vowels from multiple arguments: '{fromMultipleArguments}'");

        string fromNull = GetVowels(null);
        Console.WriteLine($"Vowels from null: '{fromNull}'");

        string fromNoValue = GetVowels();
        Console.WriteLine($"Vowels from no value: '{fromNoValue}'");
    }

    static string GetVowels(params string[]? input)
    {
        if (input == null || input.Length == 0)
        {
            return string.Empty;
        }

        char[] vowels = ['A', 'E', 'I', 'O', 'U'];
        return string.Concat(
            input.SelectMany(
                word => word.Where(letter => vowels.Contains(char.ToUpper(letter)))));
    }
}

// The example displays the following output:
//     Vowels from array: 'aeaaaea'
//     Vowels from multiple arguments: 'aeaaaea'
//     Vowels from null: ''
//     Vowels from no value: ''