我有一个自定义配置部分:
<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"]; }
}
}
答案 0 :(得分:1)
您需要向ClientElementCollection
像
这样的东西public ClientElement this[string key]
{
get
{
return this.Cast<ClientElement>()
.Single(ce=>ce.ClientAbbrev == key);
}
}