.net - 自定义 app.config 配置部分处理程序

标签 .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>

最佳答案

首先,在扩展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/

相关文章:

asp.net-core - appsettings.json 中 ConnectionString 中的 SQL 别名存在问题

c# - app.config 从其他节点读取关键连接字符串的值

c# - 如何创建文件或将文件上传到 Azure Data Lake Storage Gen2

c# - Windows 搜索 - 在 C# 中进行全文搜索

python-2.7 - 如何拦截flask中的所有异常?

c# - 创建一个只知道类名的对象?

java - 任何 Apache Commons-Configuration 替代品/竞争对手?

azure - 有没有办法使用 Slow Cheetah 来转换 Azure Worker Role 中的 app.config?

.net - c# com 对象配置最佳实践

c# - 为什么使用 EF 代码的插入首先在 TransactionScope 中失败?