0

我有一个自定义配置部分:

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

1 回答 1

1

您需要将索引器添加到ClientElementCollection

就像是

public ClientElement this[string key]
{
     get
     {
           return this.Cast<ClientElement>()
               .Single(ce=>ce.ClientAbbrev == key);
     }
}
于 2011-02-25T08:53:25.197 回答