在<dbFactory> 配置节中有两个元素
,即<default>和<factorys>
,而<factorys>元素又包含了两个子元素
。那么在这里<default>就是单一型配置元素,而<factorys>就是集合型配置元素
。我们需要分别实现与这些元素相对应的类及其属性。
  <default>元素:它是一个单一型的元素,所以我们继承ConfigurationElement。该元素中有一个factory属性,那么我们在类中进行相应的定义。代码如下:
  代码
  public class DefaultElement: ConfigurationElement
  {
  [ConfigurationProperty("factory")]
  public string Factory
  {
  get
  {
  return this["factory"] as string;
  }
  set
  {
  this["factory"] = value;
  }
  }
  }
  注意:在属性定义上面我们需要注册该属性的ConfigurationProperty特性。
  <factorys>子元素:
  代码
  public class FactoryElement : ConfigurationElement
  {
  [ConfigurationProperty( "name" )]
  public string Name
  {
  get
  {
  return this["name"] as string;
  }
  set
  {
  this["name"] = value;
  }
  }
  [ConfigurationProperty("assembly")]
  public string Assembly
  {
  get
  {
  return this["assembly"] as string;
  }
  set
  {
  this["assembly"] = value;
  }
  }
  [ConfigurationProperty("class")]
  public string Class
  {
  get
  {
  return this["class"] as string;
  }
  set
  {
  this["class"] = value;
  }
  }
  }
  <factorys>元素是集合型元素,继承ConfigurationElementCollection。
  代码
  public class FactoryElements : ConfigurationElementCollection
  {
  protected override ConfigurationElement CreateNewElement()
  {
  return new FactoryElement();
  }
  protected override object GetElementKey( ConfigurationElement element )
  {
  return ((FactoryElement)element).Name;
  }
  public FactoryElement this[string name]
  {
  get
  {
  return BaseGet( name ) as FactoryElement;
  }
  }
  }
  ConfigurationElementCollection类是个抽象类,你应该显示的实现它的CreateNewElement方法和GetElementKey方法。
  <dbFactory>节点,继承于ConfigurationSection
  代码
  public class DbFactorySection : ConfigurationSection
  {
  [ConfigurationProperty("default")]
  public DefaultElement DefaultFactory
  {
  get
  {
  return this["default"] as DefaultElement;
  }
  set
  {
  this["default"] = value;
  }
  }
  [ConfigurationProperty( "factorys" )]
  public FactoryElements Factorys
  {
  get
  {
  return this["factorys"] as FactoryElements;
  }
  set
  {
  this["factorys"] = value;
  }
  }
  }
  配置节处理程序终于写完了,把这四个类放在同一个工程目录下,编译成一个DLL。在你需要获取配置信息的地方,引用这个DLL,用DbFactorySection section = C