从web.config中的配置部分解析布尔值

Blo*_*opy 4 c# nullable

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

我的一个课程是抓住这个:

<myConfigSection LabelVisible="" TitleVisible="true"/>
Run Code Online (Sandbox Code Playgroud)

如果我有真或假,我有解析的东西,但如果属性为空,我会收到错误.当配置部分尝试将类映射到配置部分时,我在'LabelVisible'部分上得到"不是bool的有效值"的错误.

如何在myConfigSection类中将""解析为false?

我试过这个:

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

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

        }
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试使用返回的内容时:

graph.Label.Visible = myConfigSection.LabelsVisible;
Run Code Online (Sandbox Code Playgroud)

我得到一个错误:

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

jas*_*son 8

你的问题是graph.Label.Visible类型bool但是myConfigSection.LabelsVisible类型bool?.没有隐式转换bool?,bool因为这是一个缩小的转换.有几种方法可以解决这个问题:

1:铸铁myConfigSection.LabelsVisible一个bool:

graph.Label.Visible = (bool)myConfigSection.LabelsVisible;
Run Code Online (Sandbox Code Playgroud)

2:boolmyConfigSection.LabelsVisible以下位置提取基础价值:

graph.Label.Visible = myConfigSection.LabelsVisible.Value;
Run Code Online (Sandbox Code Playgroud)

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

graph.Label.Visible = myConfigSection.LabelsVisible.HasValue ?
                          myConfigSection.LabelsVisible.Value : true;
Run Code Online (Sandbox Code Playgroud)

4:将此逻辑集中到myConfigSection.LabelsVisible:

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

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


Dar*_*rov 0

if (myConfigSection.LabelsVisible.HasValue)
{
    graph.Label.Visible = myConfigSection.LabelsVisible.Value;
}
Run Code Online (Sandbox Code Playgroud)