代碼 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是不是你想要的東西呢?