在配置文件中使用自定义配置,需要在configSections中添加一个section元素,并制定此section元素对应的类型和名字。然后再在configuration根节点下面添加此自定义配置,如上例中的simple节点。simple节点只有两个整形数的属性maxValue和minValue。 要在程序中使用自定义配置我们还需要实现存取这个配置块的类型,一般需要做如下三件事: 1. 定义类型从System.Configuration.ConfigurationSection继承 2. 定义配置类的属性,这些属性需要用ConfigurationProperty特性修饰,并制定属性在配置节中的名称和其他一些限制信息 3. 通过基类的string索引器实现属性的get ,set 非常简单和自然,如下是上面配置类的实现: 复制代码 代码如下: public class SimpleSection:System.Configuration.ConfigurationSection { [ConfigurationProperty("maxValue",IsRequired=false,DefaultValue=Int32.MaxValue)] public int MaxValue { get { return (int)base["maxValue"]; } set { base["maxValue"] = value; } }
[ConfigurationProperty("minValue",IsRequired=false,DefaultValue=1)] public int MinValue { get { return (int) base["minValue"];} set { base["minValue"] = value; } }
[ConfigurationProperty("enabled",IsRequired=false,DefaultValue=true)] public bool Enable { get { return (bool)base["enabled"]; } set { base["enabled"] = value; } } }
这个配置的名字是complex,他有一个属性height,他的节点内还有一个child元素这个元素有两个属性firstName和lastName;对于这个内嵌的节点该如何实现呢?首先我们需要定义一个类,要从ConfigurationElement类继承,然后再用和SimpleSection类似的方法定义一些用ConfigurationProperty特性修饰的属性就可以了,当然属性值的get,set也要使用基类的索引器。如下实现: 复制代码 代码如下: public class ComplexSection : ConfigurationSection { [ConfigurationProperty("height", IsRequired = true)] public int Height { get { return (int)base["height"]; } set { base["height"] = value; } }
[ConfigurationProperty("child", IsDefaultCollection = false)] public ChildSection Child { get { return (ChildSection)base["child"]; } set { base["child"] = value; } } }
public class ChildSection : ConfigurationElement { [ConfigurationProperty("firstName", IsRequired = true, IsKey = true)] public string FirstName { get { return (string)base["firstName"]; } set { base["firstName"] = value; } }
[ConfigurationProperty("lastName", IsRequired = true)] public string LastName { get { return (string)base["lastName"]; } set { base["lastName"] = value; } } }
为了方便的存取sectionGroup中的section我们可以实现一个继承自System.Configuration.ConfigurationSectionGroup类的自定义类。实现很简单,就是通过基类的Sections[“sectionName”]索引器返回Section。如下: 复制代码 代码如下: public class SampleSectionGroup : System.Configuration.ConfigurationSectionGroup { public SimpleSection Simple { get { return (SimpleSection)base.Sections["simple"]; } }
public ComplexSection Complex { get { return (ComplexSection)base.Sections["complex"]; } } }