我有以下的ConfigurationProperty作为一个元素的一部分:
[ConfigurationProperty("example", IsRequired = false, DefaultValue = null)]
public string Example {
get { return (string)base["example"]; }
set { base["example"] = value; }
}
如果我按照以下方式设置它,它会采用"Hello"
字符串并正常工作:
<myElement example="Hello"/>
如果它不存在,我会遇到问题:<myElement/>
与上面指定的默认值null
不同,它采用了String.Empty
。为什么会这样,我该如何使其采用null
的默认值?
更新
它绝对是因为base["example"]
返回String.Empty
,其中base
是一个ConfigurationElement
(索引器在此处定义:https://msdn.microsoft.com/en-us/library/c8693ks1(v=vs.110).aspx),但我仍然不确定为什么它不能采用null
的值。
更新
即使DefaultValue=default(string)
也会将字符串设置为String.Empty
。
更新
甚至base.Properties.Contains("example")
如果属性不存在于配置中,则返回true
。
DefaultValue
没有被使用,但你是否尝试通过扩展属性的 getter 方法并检查base.Properties.Contains("example")
,如果为 false 则手动返回null
? - stakx - no longer contributingbase.Properties.Contains("example")
也会返回true
。 - Alexandru