我的 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.Visible
是 bool
类型,但 myConfigSection.LabelsVisible
是 bool?
。没有从 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/