当前位置:  开发笔记 > 编程语言 > 正文

自定义配置,ConfigurationElements和ConfigurationProperties

如何解决《自定义配置,ConfigurationElements和ConfigurationProperties》经验,为你挑选了1个好方法。

过去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.



1> Good Night N..:

我发现最好的方法是覆盖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.

推荐阅读
惬听风吟jyy_802
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有