自定义app.config配置节处理程序 [英] Custom app.config Config Section Handler

查看:125
本文介绍了自定义app.config配置节处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我使用像这样的app.config,那么通过继承System.Configuration.Section的类来获取页面列表的正确方法是什么?

 <?xml version =1.0encoding =utf-8?> 
< configuration>

< configSections>
< section name =XrbSettingstype =Xrb.UI.XrbSettings,Xrb.UI/>
< / configSections>

< XrbSettings>
< pages>
< add title =Googleurl =http://www.google.com/>
< add title =Yahoourl =http://www.yahoo.com/>
< / pages>
< / XrbSettings>

< / configuration>


解决方案

首先在类中添加一个属性,

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

然后你需要创建一个PageCollection类。我看到的所有例子都是相同的,所以只需复制 this one ,并将NamedService重命名为Page。

最后添加一个扩展ObjectConfigurationElement的类:



public class PageElement:ObjectConfigurationElement {
[ConfigurationProperty(title,IsRequired = true)]
public string标题{
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;
}
}
}

示例实现:




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>

解决方案

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"];
    }
}

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".

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配置节处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆