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'
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
Something like
public ClientElement this[string key]
{
get
{
return this.Cast<ClientElement>()
.Single(ce=>ce.ClientAbbrev == key);
}
}
精彩评论