前言

开发过程中我们会经常使用到各种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.执行结果

总结

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

最新文章

  1. STM32——assert_param(expr)
  2. CRect类
  3. Android实战_来电拦截专家
  4. [转] - QPixmap全局变量载入多张图片失效问题
  5. 利用NTFS交换数据流隐藏文件
  6. 一、IRIG-B 概念
  7. [转]2-SAT问题及其算法
  8. bzoj3124
  9. A标签-一个按钮样式
  10. linux下MongoDB客户端shell基本操作
  11. POJ-1915 Knight Moves (BFS)
  12. Fedora25 将eclipse的快捷方式添加到Applications中
  13. Android + HTML5 混合开发
  14. 测者的测试技术手册:Junit单元测试遇见的一个枚举类型的坑(枚举类型详解)
  15. unittest中常用的几个断言
  16. 并发编程(十二)—— Java 线程池 实现原理与源码深度解析 之 submit 方法 (二)
  17. 一键安装Lnmp教程
  18. 【nodejs】初识 NodeJS(四)
  19. C#中Equals()和= =(等于号)区别
  20. 蒙特卡罗方法 python 实现

热门文章

  1. web-php绕过
  2. 宏WINAPI和几种调用约定
  3. 将下载到本地的JAR包手动添加到Maven仓库
  4. head first python菜鸟学习笔记(第六章)
  5. [阿里云部署] Ubuntu+Flask+Nginx+uWSGI+Mysql搭建阿里云Web服务器
  6. 电子笔记本的思考(1)(ver0.3)
  7. JavaSE初步学习笔记
  8. Shell中处理方法返回值问题
  9. 关于[LeetCode]Factorial Trailing Zeroes O(logn)解法的理解
  10. webrtc视频数据解码处理流程