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

C#程序中为int变量添加const修饰符报错问题咨询

错误原因及解决办法

错误原因

C#里的const变量属于编译时常量,要求初始化值必须是编译阶段就能确定的固定值(比如int const num = 2000;这种字面量赋值)。但你的代码中,born_year的值来自用户运行时输入的Console.ReadLine(),属于只有程序运行时才能确定的动态值,完全不符合const的定义要求,因此编译器会报错。

解决办法

方案1:移除const修饰符

既然变量值是运行时动态获取的,不需要编译时常量特性,直接去掉const即可正常运行:

Console.WriteLine("What year were you born?");
int born_year = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("You were born in this year " + born_year);
Console.ReadLine();

方案2:用readonly实现运行时只读

如果希望变量初始化后不能被修改,可以改用readonly修饰符——它允许运行时初始化,且初始化后无法被后续代码修改:

Console.WriteLine("What year were you born?");
readonly int born_year = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("You were born in this year " + born_year);
Console.ReadLine();

注:readonly变量只能在声明时或者类的构造函数中赋值,适合需要运行时初始化但要限制修改的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 02:05:23