过去3天我一直在网上搜索,但找不到任何关于这个问题的提法.我已经创建了一个自定义配置类,可以与我的app.config一起使用.一切正常.当不需要配置属性(配置元素)并且未在app.config中定义时,会出现此问题.似乎为配置属性返回默认值.有谁知道如何确定app.config中是否未定义该属性?(我一直试图发布我的app.config,但无法弄清楚如何做到这一点......谁知道怎么做?)
//Main namespace TestStub { class Program { static void Main(string[] args) { CustomSettingsHandler config = (CustomSettingsHandler)ConfigurationManager.GetSection("CustomSettingsManager"); Console.WriteLine("Setting1 {0}", config.Setting1.CustomSettingItem); Console.WriteLine("Setting2 {0}", config.Setting2.CustomSettingItem); } } } //Custom Configuration Class namespace CustomConfiguration { public class CustomSettingsHandler : ConfigurationSection { [ConfigurationProperty("setting1", IsRequired = false)] public CustomSettingElement Setting1 { get { return (CustomSettingElement)this["setting1"]; } } [ConfigurationProperty("setting2", IsRequired = false)] public CustomSettingElement Setting2 { get { return (CustomSettingElement)this["setting2"]; } } } public class CustomSettingElement : ConfigurationElement { [ConfigurationProperty("customsettingitem", IsRequired = false)] public int CustomSettingItem { get { return (int)this["customsettingitem"]; } } } }
Good Night N.. 11
我发现最好的方法是覆盖ConfigurationSection.PostDeserialize()
并检查IsPresent
派生自的每个部分成员的属性ConfigurationElement
.
public class CustomSettingsHandler : ConfigurationSection { // ... protected override void PostDeserialize() { foreach (ConfigurationProperty property in Properties) { var configElement = this[property] as ConfigurationElement; if (configElement != null && !configElement.ElementInformation.IsPresent) { this[property] = null; } } base.PostDeserialize(); } }
之后ConfigurationElement
将从配置文件中读取每个null
.
我发现最好的方法是覆盖ConfigurationSection.PostDeserialize()
并检查IsPresent
派生自的每个部分成员的属性ConfigurationElement
.
public class CustomSettingsHandler : ConfigurationSection { // ... protected override void PostDeserialize() { foreach (ConfigurationProperty property in Properties) { var configElement = this[property] as ConfigurationElement; if (configElement != null && !configElement.ElementInformation.IsPresent) { this[property] = null; } } base.PostDeserialize(); } }
之后ConfigurationElement
将从配置文件中读取每个null
.