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

尝试向List<Citizen>添加对象时遇"Add方法无3参数重载"错误

解决List.Add报错"No overload for method Add takes 3 arguments"

错误原因

List<Citizen>的Add方法仅接受单个Citizen类型的实例作为参数,你直接传入name、age、country三个独立变量,不符合方法的参数定义,因此触发编译错误。

解决步骤

每次向集合添加元素时,先通过输入的参数创建Citizen对象,再将该对象传入Add方法:

修改后的Main方法代码:

static void Main(string[] args)
{
    List<Citizen> citizens = new List<Citizen>();

    string name = Console.ReadLine();
    string country = Console.ReadLine();
    int age = int.Parse(Console.ReadLine());
    // 先创建Citizen实例,再添加到集合
    citizens.Add(new Citizen(name, age, country));

    string end = Console.ReadLine().ToUpper();
    while (end != "End")
    {
        name = Console.ReadLine();
        country = Console.ReadLine();
        age = int.Parse(Console.ReadLine());
        // 同样先实例化Citizen
        citizens.Add(new Citizen(name, age, country));
        // 补充读取终止判断,避免无限循环
        end = Console.ReadLine().ToUpper();
    }
}

额外说明

原代码的循环存在无限循环风险:循环内没有重新读取end的值,会导致一旦进入循环就无法退出。上面的修改已经补充了end = Console.ReadLine().ToUpper();这一行,确保每次循环后都会判断是否终止。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 19:05:25