c# - 从 web.config 中的配置部分解析 bool 值

标签 c# nullable

我的 web.config 中有一个自定义配置部分。

我的一个类(class)正在从中获取:

<myConfigSection LabelVisible="" TitleVisible="true"/>

如果我有 true 或 false,我有一些东西可以解析,但是如果属性为空,我就会收到错误。当配置部分尝试将类映射到配置部分时,我在“LabelVisible”部分收到“不是有效的 bool 值”错误。

如何在我的 ConfigSection 类中将 ""解析为 false?

我试过这个:

    [ConfigurationProperty("labelsVisible", DefaultValue = true, IsRequired = false)]
    public bool? LabelsVisible
    {
        get
        {

            return (bool?)this["labelsVisible"];

        }

但是当我尝试使用像这样返回的内容时:

graph.Label.Visible = myConfigSection.LabelsVisible;

我得到一个错误:

'Cannot implicitly convert type 'bool?' to 'bool'. An explicit conversion exists (are you missing a cast?)  

最佳答案

您的问题是 graph.Label.Visiblebool 类型,但 myConfigSection.LabelsVisiblebool?。没有从 bool?bool 的隐式转换,因为这是一个收缩转换。有几种方法可以解决这个问题:

1:将 myConfigSection.LabelsVisible 转换为 bool:

graph.Label.Visible = (bool)myConfigSection.LabelsVisible;

2:从 myConfigSection.LabelsVisible 中提取底层的 bool 值:

graph.Label.Visible = myConfigSection.LabelsVisible.Value;

3:当myConfigSection.LabelsVisible表示null值时,添加捕获逻辑:

graph.Label.Visible = myConfigSection.LabelsVisible.HasValue ?
                          myConfigSection.LabelsVisible.Value : true;

4:将此逻辑内化到 myConfigSection.LabelsVisible:

[ConfigurationProperty("labelsVisible", DefaultValue = true, IsRequired = false)]
public bool LabelsVisible {
    get {
        bool? b= (bool?)this["labelsVisible"];
        return b.HasValue ? b.Value : true;
    }
}

这是后两种方法之一,可以最好地避免在 myConfigSection.LabelsVisible 表示 null 值时使用其他解决方案时可能发生的一些异常。最好的解决方案是将此逻辑内化到 myConfigSection.LabelsVisible 属性 getter 中。

关于c# - 从 web.config 中的配置部分解析 bool 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1675463/

相关文章:

c# - 具有可空 bool 值的三值逻辑?

c# - 使用 BinaryReader 读/写可空类型?

c# - 对 Nullable<T> 约束的困惑

c# - 一个可以分解三元表达式的工具

c# - Visual Studio 中 C# IOS 项目中的 c++ 库

c# - 冗余控制流跳转语句及跳转语句的执行

c# - .Net如何允许将Nullables设置为Null

c# - 使用 C# 解析 XML

c# - 使用已知名称注册 channel ,然后通过该已知名称检查和注销它而不终止其他应用程序 channel

c# - 如何从 DateTime 中删除值?