zoukankan      html  css  js  c++  java
  • 自定义结构化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.执行结果

    总结

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

    文中如有不对之处,欢迎指正。   
    本文版权归作者和博客园共有,欢迎转载,但请在文章页面明显位置给出原文连接。
    作者:Nuss
    出处:http://www.cnblogs.com/Nuss/
  • 相关阅读:
    10 Iterable之遍历Map、Set、Array
    9 Map和Set
    8 循环
    5 字符串
    6 数组
    4 数据类型
    2 变量
    实现简单的邮件收发器(十二)
    10.19 初识django
    10.18 数据库之索引优化方案
  • 原文地址:https://www.cnblogs.com/Nuss/p/7710074.html
Copyright © 2011-2022 走看看