C# 方法中的参数数组

前言:
有时候我们不能精确的确定一个方法需要多少个参数,
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: ''
posted @   清和时光  阅读(113)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
历史上的今天:
2022-01-12 C# 判断某个时间是星期几
2021-01-12 NET 相关知识点目录
点击右上角即可分享
微信分享提示