使用 C# 中的 const int 来配置文件。

huangapple go评论54阅读模式
英文:

Use a const int with the config file in C#

问题

在我的应用程序中,我尝试使一个变量在App.Config文件中可编辑。但是,我收到了一个错误,说无法将字符串转换为整数。

代码片段:

/* 这在.cs文件中 */
private readonly System.Timers.Timer statusEventTimer = new();
private const int statusEventTime = ConfigurationManager.AppSettings["statusTime"];

statusEventTimer.Interval = statusEventTime;
statusEventTimer.Elapsed += StatusEventTimerElapsed;
statusEventTimer.Start();

而这是在App.Config文件中:

<configuration>
  <appSettings>
    <add key="statusTime" value="3000"/>
  </appSettings>
</configuration>

我尝试使用ToInt32将statusTime转换,但没有成功。有什么猜测可以让这个工作吗?

英文:

I'm trying to make a variable in my app to be edited in the App.Config file. However I am getting a error saying: Cannot convert string to int.

Code snippet:

/* This is in the .cs file */
private readonly System.Timers.Timer statusEventTimer = new();
private const int statusEventTime = ConfigurationManager.AppSettings[&quot;statusTime&quot;];

statusEventTimer.Interval = statusEventTime;
statusEventTimer.Elapsed += StatusEventTimerElapsed;
statusEventTimer.Start();

And this is in the App.Config file

&lt;configuration&gt;
  &lt;appSettings&gt;
	&lt;add key=&quot;statusTime&quot; value=&quot;3000&quot;/&gt;
  &lt;/appSettings&gt;
&lt;/configuration&gt;

I've tried to convert the statusTime using ToInt32 but no luck here. Any guesses on what I can do to make this work?

答案1

得分: 4

有两个问题与此代码相关:首先,正如其他人在评论中提到的,配置文件中的字符串可能根本无法解析为整数值 - 没有任何阻止部署您软件的人使用"Banana"作为statusTime的值。

另一个问题是,在C#中,常量必须在编译时知道。实际上,编译器在编译C#程序时会用其值替换常量的任何出现。

因此,您不能使用配置中的值来定义您的常量。然而,您可以将常量更改为静态只读字段 - 它几乎具有常量的所有优点,但可以在运行时获取其值,这意味着它也可以用于保存在编译时不知道的值。

因此,总结一下 - 与其使用:

private const int statusEventTime = ConfigurationManager.AppSettings[&quot;statusTime&quot;];

请使用:

private static readonly int statusEventTime =  
    int.Parse(ConfigurationManager.AppSettings[&quot;statusTime&quot;]);

也就是说,如果要在配置中的statusTime的值无法解析为整数时抛出异常。

如果您确实希望在值未正确配置的情况下使用默认的硬编码值,请使用int.TryParse,如下所示:

private const int defaultStatusEventTime = 3000; // 或者任何其他值...
private static readonly int statusEventTime =  
    int.TryParse(ConfigurationManager.AppSettings[&quot;statusTime&quot;], out var statusTime) 
        ? statusTime 
        : defaultStatusEventTime;
英文:

There are two problems with this code: The first, as others have mentioned in comments, is that the string in configuration file might not be parsable as an int value at all - nothing is stopping whoever is deploying your software to use "Banana" as the value for statusTime.

The other problem is that constants in c# must be known at compile time. In fact, the compiler is replacing any occurrence of the constant with its value while compiling the c# program.
therefore, you can't use values from configuration for your constants.
What you can do, however, is change the constant to a static readonly field - which have almost all the advantages of constants but can take its value at run time, meaning it can also be used to hold values that aren't known at compile time.

So, to conclude - instead of

private const int statusEventTime = ConfigurationManager.AppSettings[&quot;statusTime&quot;];

use

private static readonly int statusEventTime =  
    int.Parse(ConfigurationManager.AppSettings[&quot;statusTime&quot;]);

That is, if you want an exception thrown if the value of statusTime in configuration isn't parsable as an int.
If you do want to have a default, hard coded value to use in cases where the value isn't configured properly, use int.TryParse like this:

private const int defaultStatusEventTime = 3000; // or any other value, for that matter...
private static readonly int statusEventTime =  
    int.TryParse(ConfigurationManager.AppSettings[&quot;statusTime&quot;], out var statusTime) 
        ? statusTime 
        : defaultStatusEventTime;

huangapple
  • 本文由 发表于 2023年6月1日 17:27:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/76380458.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定