代码 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 = ConfigurationManager.GetSection( "dbFactory" ) as DbFactorySection;试试,section是不是你想要的东西呢?