【问题标题】:C# Custom Config SectionC# 自定义配置部分
【发布时间】:2011-07-04 04:00:45
【问题描述】:

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

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

【问题讨论】:

    标签: c# configuration configurationsection


    【解决方案1】:

    您需要将indexer 添加到ClientElementCollection

    类似

    public ClientElement this[string key]
    {
         get
         {
               return this.Cast<ClientElement>()
                   .Single(ce=>ce.ClientAbbrev == key);
         }
    }
    

    【讨论】:

    • 谢谢。我确实发现,如果我在 ClientElement 中为 ClientAbbrev 属性设置 ConfigurationProperty 的“IsKey”属性,我的索引器可能是:
    • public new ClientElement this[string clientAbbreviation] { get { return (ClientElement) BaseGet(clientAbbreviation); } }
    猜你喜欢
    • 2010-10-25
    • 2012-10-04
    • 2010-11-12
    • 2013-09-17
    • 2012-12-12
    • 2013-09-21
    • 2016-07-20
    • 2014-01-19
    相关资源
    最近更新 更多