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

C#如何正确将字符串转换为int类型并输入到列表中?

代码问题分析
  • 第一类编译错误:Int32.Parse() 仅支持传入符合整数格式的字符串作为参数,你的代码中已经通过Convert.ToInt32(Console.ReadLine())将用户输入转为int类型的input变量,再把int类型变量传给Parse方法,类型不匹配会直接触发编译失败。
  • 第二类逻辑错误:循环判断条件为input >=0时继续执行,你在循环体内先读取用户输入转成int赋值给input,再直接添加到列表,会导致最后输入的负数也被存入列表,不符合需求。

Convert.ToInt32 与 Int32.Parse 功能区别
  • Int32.Parse(string s):仅接收字符串类型输入,要求输入字符串必须严格匹配整数格式:输入为null时抛ArgumentNullException、输入格式不匹配抛FormatException、数值超出int取值范围抛OverflowException。
  • Convert.ToInt32(object value):可接收所有基础类型输入(字符串、数值、布尔值、null等),输入为null时会直接返回0而非抛异常;如果输入为字符串类型,内部本质还是调用Int32.Parse完成转换。

修正后代码
using System;
using System.Collections.Generic;

namespace Chapter
{
    class Program
    {
        static void Main()
        {
            List<int> numbers = new List<int>();
            while (true)
            {
                Console.WriteLine("Input number: ");
                string inputStr = Console.ReadLine();
                // 先做格式校验,避免非法输入崩溃
                if (!Int32.TryParse(inputStr, out int input))
                {
                    Console.WriteLine("请输入合法整数");
                    continue;
                }
                // 输入小于0直接终止循环,不存入列表
                if (input < 0)
                {
                    break;
                }
                numbers.Add(input);
            }

            Console.WriteLine("the numbers you have input are");
            foreach (int number in numbers)
            {
                Console.Write(number + " ");
            }
        }
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 21:24:02