Раздел пользовательской конфигурации C #

У меня есть настраиваемый раздел конфигурации:

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

person David Ward    schedule 25.02.2011    source источник


Ответы (1)


Вам необходимо добавить индексатор в ClientElementCollection

Что-то типа

public ClientElement this[string key]
{
     get
     {
           return this.Cast<ClientElement>()
               .Single(ce=>ce.ClientAbbrev == key);
     }
}
person Richard Friend    schedule 25.02.2011
comment
Спасибо. Я обнаружил, что если я установлю атрибут IsKey ConfigurationProperty для свойства ClientAbbrev в ClientElement, мой индексатор может быть: - person David Ward; 25.02.2011
comment
общедоступный новый ClientElement это [строка clientAbbreviation] {получить {return (ClientElement) BaseGet (clientAbbreviation); }} - person David Ward; 25.02.2011