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"]; }
}
}
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"]; }
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要添加索引器
ClientElementCollection
类似于
You need to add an indexer to
ClientElementCollection
Something like