【问题标题】:Custom config section with two differentt child collections具有两个不同子集合的自定义配置部分
【发布时间】:2012-11-04 15:48:52
【问题描述】:

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

<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'。

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

【问题讨论】:

  • 你的第一个有ConfigurationCollection(typeof(TemplateCollection), ...,你的第二个有ConfigurationCollection(typeof(SubItem2Collection), ...
  • @Thymine。错字。显然我的收藏实际上并不称为“SubItem2Collection”。我只是将它们重命名以消除对我要实现的目标的任何混淆。
  • 啊我想知道他们是否都应该是TemplateCollection,而不是在两者之间改变。正在考虑这样的错字也可能导致原始代码中的转换错误。我之前只需要一个配置中的 1 个非默认集合,因此不确定是否有更好的解决方案,所以我想指出这一点:)
  • @Thymine 感谢您的指出。我在同一条船上,只需要一个集合。 fsimonazzi 的回答正是问题所在。我很惊讶网络上的真实示例如此之少。

标签: c# .net configuration-files custom-configuration configsection


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2011-11-04
    • 2011-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多