【发布时间】: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