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
相关产品推荐
相关产品推荐

