C#中用const int读取App.Config报错:无法将字符串转换为int
解决“无法将字符串转换为int”的配置读取问题
你的错误根源有两个:
const修饰的变量必须是编译时常量:ConfigurationManager.AppSettings["statusTime"]是运行时才会读取的配置值,无法在编译阶段确定,因此不能用来初始化const变量。- 缺少显式类型转换:
AppSettings返回的是字符串类型,直接赋值给int类型变量会触发类型转换错误。
修正后的基础写法
/* This is in the .cs file */ private readonly System.Timers.Timer statusEventTimer = new(); // 去掉const,改用readonly保留只读特性,同时显式转换配置值 private readonly int statusEventTime = int.Parse(ConfigurationManager.AppSettings["statusTime"]); statusEventTimer.Interval = statusEventTime; statusEventTimer.Elapsed += StatusEventTimerElapsed; statusEventTimer.Start();
更健壮的容错写法
如果担心配置项缺失或值不是合法整数,可以添加默认值和异常处理,避免程序崩溃:
private readonly System.Timers.Timer statusEventTimer = new(); private readonly int statusEventTime; public YourClassName() // 在类的构造函数中完成初始化 { // 尝试转换配置值,失败则使用默认值3000 if (int.TryParse(ConfigurationManager.AppSettings["statusTime"], out int time)) { statusEventTime = time; } else { statusEventTime = 3000; } statusEventTimer.Interval = statusEventTime; statusEventTimer.Elapsed += StatusEventTimerElapsed; statusEventTimer.Start(); }
补充说明
int.Parse会在转换失败时抛出异常,适合确定配置值一定合法的场景。int.TryParse不会抛出异常,返回转换是否成功,适合需要容错的场景。- 运行时动态读取的配置值,永远不要用
const修饰,改用readonly或普通字段即可。
内容的提问来源于stack exchange,提问作者mohammed_sajid
相关产品推荐
相关产品推荐

