一、原来自定配置文件的编写方式:
1、定义类型比较繁琐
internal class AOPConfigurationSection : ConfigurationSection { [ConfigurationProperty("", IsDefaultCollection = true)] public AopElementCollection Aops //需要定义这里略 { get { return (AopElementCollection)base[""]; } } }
2、LINQ TO XML查询
XElement xelement = XElement.Parse(xml); var name = from e in xelement.Elements("b") let s = e.Element("e") select s.Attribute("name").Value;
二、通用配置组件介绍
引用:DefinitionConfig.dll
对象:
DisplayConfigName特性(对应节点名称)
ReadSection类(初始化节点)
ConfigSectionsHelper类(配置解析类)
Sections类(配置集合类)
特点:根据自定义类型读取配置文件
注意:定义属性为string或class类型,集合为泛型Sections类
方法:GetConfigSection
GetConfigSectionChild
1.自定义类型
public class ConnConfig { [DisplayConfigName("name")]//配置文件中名称为name public string Name { get; set; } public string str{ get; set; }//如果没有声明特性,那么配置文件名称为属性名称str }
2.单节点(不含子节点)
//这里section 中type属性为DefinitionConfig.ConfigSectionsHelper,DefinitionConfig
或
上面我们只配置了一个connstr节点。没有任何子节点。注:此节点只能有一个,所以不能多个connstr。
我们把这个配置读取为ConnConfig类型。
ReadSection rs = new ReadSection("connstr");//实例化ReadSection,参数为节点名称
ConnConfig conn= rs.GetConfigSection
Console.WriteLine(conn.Name);//验证是否读取到
3、多节点(含子节点)
ReadSection rs = new ReadSection("connstrs");//读取connstrs节点 var con = rs.GetConfigSectionChild
4、属性为自定义类型(含多个子节点)
public class ConnConfig { [DisplayConfigName("name")] public string Name { get; set; } public ConnString str { get; set; }//定义为类型 }
public class ConnString { public string name { get; set; } public string type { get; set; } }
ReadSection rs = new ReadSection("connstrs"); var con = rs.GetConfigSectionChild
5、属性为自定义集合类型(子节点集合)
public class ConnConfig { [DisplayConfigName("name")] public string Name { get; set; } public ConnString str { get; set; } public Sections
public class ConnString { public string name { get; set; } public string type { get; set; } }
public class AA{ public string name{get;set;} }
ReadSection rs = new ReadSection("connstrs"); var con = rs.GetConfigSectionChild
6、属性为自定义多个集合类型(多子节点集合)
public class ConnConfig { [DisplayConfigName("name")] public string Name { get; set; } public ConnString str { get; set; } public Sections
public class ConnString { public string name { get; set; } public string type { get; set; } }
public class AA { public string name { get; set; } public Sections
public class BB { public string type { get; set; } }
ReadSection rs = new ReadSection("connstrs"); var con = rs.GetConfigSectionChild
7、配置外部config
ReadSection rs = new ReadSection("mySection");//读取节点 var list = rs.GetConfigSectionChild
组件下载:DefinitionConfig
组件Demo:ReadConfigDemo
最新评论