问题描述
如果我使用这样的 app.config,通过继承自 System.Configuration.Section 的类获取页面"列表的正确方法是什么?
What is the correct way to pick up the list of "pages" via a class that inherits from System.Configuration.Section if I used a app.config like this?
<?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 的类中添加一个属性:
First you add a property in the class that extends Section:
[ConfigurationProperty("pages", IsDefaultCollection = false)]
[ConfigurationCollection(typeof(PageCollection), AddItemName = "add")]
public PageCollection Pages {
get {
return (PageCollection) this["pages"];
}
}
然后你需要创建一个 PageCollection 类.我看到的所有示例都非常相似,因此只需复制 这个 并将NamedService"重命名为Page".
Then you need to make a PageCollection class. All the examples I've seen are pretty much identical so just copy this one and rename "NamedService" to "Page".
最后添加一个扩展ObjectConfigurationElement的类:
Finally add a class that extends 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;
}
}
}
以下是示例实现中的一些文件:
Here are some files from a sample implementation:
这篇关于自定义 app.config 配置部分处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!