31

如果我使用这样的 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>
4

1 回答 1

30

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

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

然后你需要创建一个 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;
        }
    }
}

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

于 2009-04-17T04:26:31.663 回答