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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/758986/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 12:31:58  来源:igfitidea点击:

Custom app.config Config Section Handler

.netconfigurationapp-configconfigsection

提问by BuddyJoe

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?

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

采纳答案by Luke Quinane

First you add a property in the class that extends Section:

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

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

Then you need to make a PageCollection class. All the examples I've seen are pretty much identical so just copy this oneand rename "NamedService" to "Page".

然后你需要创建一个 PageCollection 类。我见过的所有示例都几乎相同,因此只需复制示例并将“NamedService”重命名为“Page”。

Finally add a class that extends ObjectConfigurationElement:

最后添加一个扩展 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:

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