自定义结构化config文件

前言

开发过程中我们会经常使用到各种config文件,经常我们会使用appSettings进行设置所用的配置,但是随着配置量的增多,都放在appSettings里面明显是不合适的,一方面配置容易混乱,另一方面阅读性也比较低。如何优雅的设置配置文件呢?
微软提供了标准的类库System.Configuration

主要用到的类

  • ConfigurationSection :配置域
  • ConfigurationElementCollection :节点列表
  • ConfigurationElement :节点

自定义config(可根据自己需求设计)

主体实现如下

1.创建配置域MyConfiguration 继承ConfigurationSection类,,对应上图中节点信息

public class MyConfiguration : ConfigurationSection
{
    [ConfigurationProperty("Decription",IsRequired = true)]
    public string Decription
    {
        get { return (string) base["Decription"]; }
    }

    [ConfigurationProperty("Items", IsRequired = true)]
    public MyElementCollection Items
    {
        get { return this["Items"] as MyElementCollection; }
    }


    public static  MyConfiguration CurrentConfiguration
    {
        get {return ConfigurationManager.GetSection("myConfiguration") as MyConfiguration;}
    }

}

2.创建配置列表类MyElementCollection,继承ConfigurationElementCollection,对应上图中节点信息

public class MyElementCollection : ConfigurationElementCollection
{
    protected override ConfigurationElement CreateNewElement()
    {
        return new MyElement();
    }

    protected override object GetElementKey(ConfigurationElement element)
    {
        return ((MyElement)element).Name;
    }

    public MyElement Get(string name)
    {
        return (MyElement)BaseGet(name);
    }

}

3.创建配置节点信息MyElement,继承ConfigurationElement类,对应上图中配置

public class MyElement : ConfigurationElement
{
    [ConfigurationProperty("name", IsRequired = true)]
    public string Name
    {
        get { return this["name"] as string; }
    }

    [ConfigurationProperty("type", IsRequired = true)]
    public string Type
    {
        get { return this["type"] as string; }
    }
}

4.具体使用

        MyConfiguration config = MyConfiguration.CurrentConfiguration;
        Console .WriteLine("Decription:" + config.Decription);
        foreach (MyElement item in config.Items)
        {
            Console.Write(item.Name +" ");
            Console.WriteLine(item.Type);
        }

5.执行结果

总结

自定义结构化配置文件,一方面,提高可读性,另一方面,也有助于我们理解整个配置文件,理解很多第三方库为啥要加一些配置了。

posted @ 2017-10-22 15:52  Nuss  阅读(371)  评论(0编辑  收藏  举报