You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#如何正确向函数传递int数组?调用方法报CS1501错误如何解决

错误原因

CS1501报错由方法定义与调用的参数不匹配导致:

  • 已定义的Solution方法仅接收1个int[]类型的数组参数
  • 调用时直接传入6个独立int值,未封装为数组,编译器无法匹配到可接收6个int参数的Solution重载,触发报错。
两种解决方案

方案1:调用时手动封装数组

无需修改Solution方法定义,仅调整Main中的调用代码,将传入参数用new int[] { }包装为数组即可:

public static void Main()
{
    Console.WriteLine(Solution(new int[] { 1, 3, 6, 4, 1, 2 }));
}

该方案适合方法已对外暴露、不可随意修改签名的场景。

方案2:添加params关键字支持可变数量参数

如果希望直接传入任意数量的int值、无需手动封装数组,可修改Solution的方法签名,在参数前增加params关键字:

public static int Solution(params int[] input)
{
    // 方法内部原有逻辑无需做任何修改
    Array.Sort(input);

    int index = 0;

    // Skip negatives
    while (index < input.Length && input[index] < 1)
        index++;

    int expected = 1;
    while (index < input.Length)
    {
        if (input[index] > expected)
            return expected;

        // Skip number and all duplicates
        while (index < input.Length && input[index] == expected)
            index++;

        expected++;
    }

    return expected;
}

添加params后,编译器会自动将传入的多个独立int值打包为数组,原有调用逻辑可直接正常运行,同时也仍支持直接传入int数组作为参数,两种调用方式兼容。

内容的提问来源于stack exchange,提问作者user10422085

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 22:24:00