简体   繁体   English

C#自定义配置部分

[英]C# Custom Config Section

I have a custom config section: 我有一个自定义配置部分:

  <myServices>
      <client clientAbbrev="ABC">
        <addressService url="www.somewhere.com" username="abc" password="abc"/>
      </client>
      <client clientAbbrev="XYZ">
        <addressService url="www.somewhereelse.com" username="xyz" password="xyz"/>
      </client>
  <myServices>

I want to refer to the config as: 我想将配置称为:

var section = ConfigurationManager.GetSection("myServices") as ServicesConfigurationSection;
var abc = section.Clients["ABC"];

but get a 但是得到一个

cannot apply indexing to an expression of type 'ClientElementCollection' 无法将索引应用于“ ClientElementCollection”类型的表达式

How can I make this work? 我该如何进行这项工作?

client element collection: 客户元素集合:

[ConfigurationCollection(typeof(ClientElement), AddItemName = "client")]
public class ClientElementCollection : ConfigurationElementCollection
{
    protected override ConfigurationElement CreateNewElement()
    {
        return new ClientElement();
    }

    protected override object GetElementKey(ConfigurationElement element)
    {
        return ((ClientElement) element).ClientAbbrev;
    }
}

Client element: 客户元素:

public class ClientElement : ConfigurationElement
{
    [ConfigurationProperty("clientAbbrev", IsRequired = true)]
    public string ClientAbbrev
    {
        get { return (string) this["clientAbbrev"]; }
    }

    [ConfigurationProperty("addressService")]
    public AddressServiceElement AddressService
    {
        get { return (AddressServiceElement) this["addressService"]; }
    }
}

You need to add an indexer to ClientElementCollection 您需要将索引器添加到ClientElementCollection

Something like 就像是

public ClientElement this[string key]
{
     get
     {
           return this.Cast<ClientElement>()
               .Single(ce=>ce.ClientAbbrev == key);
     }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM