c# - 在 Settings.settings 中更改设置的数据类型

标签 c# winforms configurationmanager

编辑

我已经改变了我对设置的使用

private int _Capacity = ConfigurationManager.AppSettings["FuelTankCapacity"];

为了...

private int _Capacity = Convert.ToInt32(ConfigurationManager.AppSettings["FuelTankCapacity"]);

这解决了问题,但感觉像是一个懒惰的修复。必须有一种方法来指定设置的整数类型,不是吗?

原始问题

在我的 winforms 应用程序中创建了一些设置后,我在使用其中一个时遇到了一些问题。

该设置用于指定油箱的最大容量,值为2000(2000 升)。

不幸的是,设置被读取为字符串值而不是 int,即使我指定它应该是一个整数值。

这是此设置的 App.config 代码:

<setting name="FuelTankCapacity" serializeAs="String">
    <value>2000</value>
</setting>

请注意,将 SerializeAs 值更改为 int/Int32 并不能解决问题。 Here's the Settings.settings screen

最佳答案

我猜问题是 AppSettingsNameValueCollection 类型,根据 MSDN

a collection of associated String keys and String values that can be accessed either with the key or with the index.

所以采用这条路线你最终不可避免地会得到一个字符串。

使用 Property 命名空间,您可以通过 Settings 直接访问变量,从而访问您指定的类型:

int t = Properties.Settings.Default.FuelTankCapacity;

这里有更多关于 using settings at runtime 的信息

You can access the value of settings with application scope on a read-only basis, and you can read and write the values of user-scope settings. Settings are available in C# through the Properties namespace.

关于c# - 在 Settings.settings 中更改设置的数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44151612/

相关文章:

c# - Adventure Works 访问客户信息

c# - Roslyn 在 {SomeSyntax}.Type 下获取详细信息

c# - 简单的电话号码正则表达式,以零开头(可选),没有分隔符

c# - 将 Drawline 图像绘制到 Picturebox 图像中

c# - WinForms.Charting 抑制自动生成图例

.net - 用 Visual Basic 编写的 Windows 窗体应用程序是否也需要 VB 运行时?

.net - 将项目构建配置更改为 Debug模式

c# - List<Enum> in Aggregates Entity Framework Code First

c# - 为什么 Encoding.ASCII != ASCIIEncoding.Default 在 C# 中?

C# ConfigurationManager.GetSection 无法加载文件或程序集