C# 从web.config中的配置部分解析布尔值
我的web.config中有一个自定义配置部分 我的一门课是从以下内容中获得的:C# 从web.config中的配置部分解析布尔值,c#,nullable,C#,Nullable,我的web.config中有一个自定义配置部分 我的一门课是从以下内容中获得的: <myConfigSection LabelVisible="" TitleVisible="true"/> 但当我尝试使用返回的内容时: graph.Label.Visible = myConfigSection.LabelsVisible; 我得到一个错误: 'Cannot implicitly convert type 'bool?' to 'bool'. An explicit conver
<myConfigSection LabelVisible="" TitleVisible="true"/>
但当我尝试使用返回的内容时:
graph.Label.Visible = myConfigSection.LabelsVisible;
我得到一个错误:
'Cannot implicitly convert type 'bool?' to 'bool'. An explicit conversion exists (are you missing a cast?)
这有点危险,但从技术上讲是可行的:(如果nullable的值确实为null,您将得到一个invalidoOperationException): 您应该验证nullable以查看是否已设置:
bool defaultValue = true;
graph.Label.Visible = myConfigSection.LabelsVisible ?? defaultValue;
尝试:
您的问题是
graph.Label.Visible
属于bool
类型,但myConfigSection.labelvisible
属于bool?
类型。没有从bool?
到bool
的隐式转换,因为这是一个缩小的转换。有几种方法可以解决此问题:
1:将myConfigSection.LabelsVisible转换为一个bool
:
graph.Label.Visible = (bool)myConfigSection.LabelsVisible;
2:从myConfigSection.LabelsVisible中提取底层的bool
值:
graph.Label.Visible = myConfigSection.LabelsVisible.Value;
[ConfigurationProperty("labelsVisible", DefaultValue = true, IsRequired = false)]
public bool LabelsVisible {
get {
bool? b= (bool?)this["labelsVisible"];
return b.HasValue ? b.Value : true;
}
}
3:添加逻辑以在myConfigSection时捕获。LabelsVisible
表示null
值:
graph.Label.Visible = myConfigSection.LabelsVisible.HasValue ?
myConfigSection.LabelsVisible.Value : true;
4:将此逻辑内部化为myConfigSection.LabelsVisible:
graph.Label.Visible = myConfigSection.LabelsVisible.Value;
[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中。其他版本是:graph.Label.Visible=myConfigSection.LabelsVisible.Value??虚假的@jaloplo:No.myConfigSection.LabelsVisible.Value
的类型为bool
,但??
运算符保留给引用类型的左侧操作数。感谢您的解释。这是非常有帮助的。“bool”结尾的“?”具体叫什么?NullableType?语法T?
其中T
是值类型,是表示Nullable
的一种简短方式。如果myconfig.LabelsVisible.HasValue
为false
,则graph.Label.Visible
不会更改其值。OP没有在其配置文件中指定caseLabelVisible=“
中所需的行为。
graph.Label.Visible = myConfigSection.LabelsVisible.HasValue ?
myConfigSection.LabelsVisible.Value : true;
[ConfigurationProperty("labelsVisible", DefaultValue = true, IsRequired = false)]
public bool LabelsVisible {
get {
bool? b= (bool?)this["labelsVisible"];
return b.HasValue ? b.Value : true;
}
}