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

时间:2009-11-04 17:39:53

标签: c# nullable

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

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

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

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

如何在myConfigSection类中将“”解析为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?)  

4 个答案:

答案 0 :(得分:8)

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

1:将myConfigSection.LabelsVisible投射到bool

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

2:从bool中提取基础myConfigSection.LabelsVisible值:

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。

答案 1 :(得分:3)

这有点危险,但技术上有效:(如果可为空的值确实为null,则会得到InvalidOperationException):

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

您应该验证可以为空的Nullable是否已设置:

bool defaultValue = true;
graph.Label.Visible = myConfigSection.LabelsVisible ?? defaultValue;

答案 2 :(得分:2)

尝试:

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

答案 3 :(得分:0)

if (myConfigSection.LabelsVisible.HasValue)
{
    graph.Label.Visible = myConfigSection.LabelsVisible.Value;
}
相关问题