如果我使用这样的 app.config,通过继承自 System.Configuration.Section 的类获取“页面”列表的正确方法是什么?
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="XrbSettings" type="Xrb.UI.XrbSettings,Xrb.UI" />
</configSections>
<XrbSettings>
<pages>
<add title="Google" url="http://www.google.com" />
<add title="Yahoo" url="http://www.yahoo.com" />
</pages>
</XrbSettings>
</configuration>
最佳答案
首先,在扩展Section的类中添加一个属性:
[ConfigurationProperty("pages", IsDefaultCollection = false)]
[ConfigurationCollection(typeof(PageCollection), AddItemName = "add")]
public PageCollection Pages {
get {
return (PageCollection) this["pages"];
}
}
然后你需要创建一个PageCollection类。我见过的所有示例都几乎相同,因此只需复制 this one并将“NamedService”重命名为“Page”。
最后添加一个扩展ObjectConfigurationElement的类:
public class PageElement : ObjectConfigurationElement {
[ConfigurationProperty("title", IsRequired = true)]
public string Title {
get {
return (string) this["title"];
}
set {
this["title"] = value;
}
}
[ConfigurationProperty("url", IsRequired = true)]
public string Url {
get {
return (string) this["url"];
}
set {
this["url"] = value;
}
}
}
以下是示例实现中的一些文件:
关于.net - 自定义 app.config 配置部分处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/758986/