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

如何向void类型方法传入int数组?解决CS0029类型转换错误

问题解决:ATM Insert方法调用错误及逻辑修正

错误根源

CS0029 Cannot implicitly convert type 'void' to 'int' 错误的核心原因:
你在Main方法中试图将**无返回值(void)**的Insert方法的执行结果,赋值给int类型的atm.Balance属性,类型完全不匹配,导致编译器报错。

调用代码修正

直接移除赋值操作即可,因为Insert方法内部已经会更新this.Balance:

static void Main(string[] args)
{
// some other code here
    Console.WriteLine("\nEnter the amount to deposit: ");
    atm.Insert(Array.ConvertAll(Console.ReadLine().Trim().Split(' '), Convert.ToInt32));
}

Insert方法的逻辑错误修正

除了调用问题,你的Insert方法还有两处逻辑bug:

  1. 传入数组被无意义覆盖:你在方法内部通过循环重新给cash数组赋值,完全覆盖了Main方法传入的用户输入数组,等于之前的Array.ConvertAll(...)操作无效。
  2. 合法性判断逻辑颠倒:cash.Intersect(AcceptableBanknotes).Any()是判断数组中是否存在合法钞票,此时抛出异常完全错误,应该判断是否存在不合法的钞票。

修正后的Insert方法:

public void Insert(int[] cash) //I cannot change the type or parameter of the method
{
    // 移除覆盖传入数组的代码,保留Main传入的用户输入
    // for (int i = 0; i < cash.Length; i++) 
    // {
    //     cash[i] = Convert.ToInt32(Console.In.ReadLine());
    // }

    // 判断是否存在不被接受的钞票
    bool hasUnacceptableBanknote = cash.Any(note => !AcceptableBanknotes.Contains(note));
    
    if (hasUnacceptableBanknote)
    {
        throw new ArgumentException("Only acceptable banknotes are 5, 10, 20, 50 and 100");
    }
    
    this.Balance += cash.Sum(); // 累加余额
    Console.Write(this.Balance);
}

内容的提问来源于stack exchange,提问作者Renārs Abeļūns

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 05:46:04