C#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>
我想将配置称为:
var section = ConfigurationManager.GetSection("myServices") as ServicesConfigurationSection;
var abc = section.Clients["ABC"];
但得到一个   无法将索引应用于表达式   'ClientElementCollection'类型 我怎样才能做到这一点? 客户元素集合:
[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;
    }
}
客户元素:
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"]; }
    }
}
    
已邀请:
你需要添加一个索引器到
ClientElementCollection
就像是
public ClientElement this[string key]
{
     get
     {
           return this.Cast<ClientElement>()
               .Single(ce=>ce.ClientAbbrev == key);
     }
}
    

要回复问题请先登录注册