最近三天我一直在网上搜索,找不到任何关于这个问题的参考资料。我创建了一个自定义配置类以与我的 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"]; } }
}
}