自定义app.config配置节处理程序

Bud*_*Joe 31 .net configuration app-config configsection

如果我使用像这样的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>
Run Code Online (Sandbox Code Playgroud)

Luk*_*ane 28

首先,在扩展Section的类中添加一个属性:

[ConfigurationProperty("pages", IsDefaultCollection = false)]
[ConfigurationCollection(typeof(PageCollection), AddItemName = "add")]
public PageCollection Pages {
    get {
        return (PageCollection) this["pages"];
    }
}
Run Code Online (Sandbox Code Playgroud)

然后你需要创建一个PageCollection类.我看到的所有示例都非常相同,所以只需复制一个并将"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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

以下是示例实现中的一些文件:


mar*_*c_s 9

您还应该查看Jon Rista关于CodeProject上.NET 2.0配置的三部分系列.

强烈推荐,写得很好,非常有帮助!