12

我有一个基于某些类的自定义配置。我的问题是我收到一条错误消息,指出无法识别配置元素。课程如下:

[ConfigurationCollection(typeof(SectionItem), AddItemName = "Item", CollectionType = ConfigurationElementCollectionType.BasicMap)]
public class Sections : ConfigurationElementCollection
{
    public SectionItem this[int index]
    {
        get { return BaseGet(index) as SectionItem; }
        set
        {
            if (BaseGet(index) != null)
            {
                BaseRemoveAt(index);
            }
            BaseAdd(index, value);
        }
    }

    public new SectionItem this[string response]
    {
        get { return (SectionItem)BaseGet(response); }
        set
        {
            if (BaseGet(response) != null)
            {
                BaseRemoveAt(BaseIndexOf(BaseGet(response)));
            }
            BaseAdd(value);
        }
    }

    protected override ConfigurationElement CreateNewElement()
    {
        return new SectionItem();
    }

    protected override object GetElementKey(ConfigurationElement element)
    {
        return ((SectionItem)element).Key;
    }
  }

SectionItem班级:

public class SectionItem : ConfigurationElement
{
    [ConfigurationProperty("key", IsRequired = true, IsKey = true)]
    public string Key
    {
        get { return this["key"] as string; }
    }
}

SectionItems如果我在Sections类中添加对我不起作用的类型的配置属性,因为我想在配置文件的标记SectonItems内有多个。Section我已经寻找解决方案,但我发现的一切都没有解决这个问题。为了更好地理解我要实现的目标,这是我的配置的外观:

<configuration>
 <configSections>
  <section name="AdminConfig" type="XmlTest.AdminConfig, XmlTest"/>
 </configSections>
 <startup> 
     <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
 </startup>

<AdminConfig>
 <Field name="field1" key="12345" path="asd"/>
  <Section>
    <Item key="12345"/>
    <Item key="54321"/>
  </Section>
 </AdminConfig>  
</configuration>
4

1 回答 1

16

好的,所以我发现了问题。虽然Sections类有这个[ConfigurationCollection(typeof(SectionItem), AddItemName = "Item", CollectionType = ConfigurationElementCollectionType.BasicMap)]我不得不在ConfigurationSection类中注释属性,如下所示:

 [ConfigurationProperty("Section")]
 [ConfigurationCollection(typeof(Sections), AddItemName = "Item")]
 public Sections Sections
 {
    get
    {
      return (Sections)this["Section"];
    }
 }

现在项目已被识别,并且工作正常。

于 2013-10-01T11:25:12.303 回答