2

我无法找到/弄清楚如何映射以下自定义配置部分:

<section>
    <collection1>
        <subitem1 ... />
        <subitem1 ... />
    </collection1>
    <collection2>
        <subitem2 ... />
        <subitem2 ... />
    </collection2>
</section>

对于单个子集合,以下可能会起作用:

public class Section : ConfigurationSection
{
    [ConfigurationProperty("", IsRequired = true, IsDefaultCollection = true)]
    [ConfigurationCollection(typeof(SubItem1Collection), AddItemName = "collection1")]
    public SubItem1Collection Collection1
    {
        get { return (SubItem1Collection)this[string.Empty]; }
        set { this[string.Empty] = value; }
    }
}

当我尝试添加第二个集合时,它不会运行。

public class Section : ConfigurationSection
{
    [ConfigurationProperty("", IsRequired = true, IsDefaultCollection = true)]
    [ConfigurationCollection(typeof(TemplateCollection), AddItemName = "collection1")]
    public SubItem1Collection Collection1
    {
        get { return (SubItem1Collection)this[string.Empty]; }
        set { this[string.Empty] = value; }
    }

    [ConfigurationProperty("", IsRequired = true, IsDefaultCollection = true)]
    [ConfigurationCollection(typeof(SubItem2Collection), AddItemName = "collection2")]
    public SubItem2Collection Collection2
    {
        get { return (SubItem2Collection)this[string.Empty]; }
        set { this[string.Empty] = value; }
    }
}

错误是:

无法将“SubItem1Collection”类型的对象转换为“SubItem2Collection”类型。

错误显然在 indexer 中this[string.Empty];。有人能指出我正确的方向吗?

4

1 回答 1

3

您不能有两个默认集合。要使配置类与您的 xml 示例匹配,您必须分别分配名称“collection1”和“collection2”而不仅仅是“”,并在 ConfigurationProperty 属性中将 IsDefaultCollection 设置为 false,并将 AddItemName 设置为“subitem1”和“subitem2” " 用于 ConfigurationCollection 属性。还要修复@thymine 指出的关于第二个集合类型的内容。

于 2012-11-15T23:21:27.127 回答