我想在我的 web.config 中有一个自定义部分,如下所示:
<MyMainSection attributeForMainSection = "value foo">
<add name = "foo"
type = "The.System.Type.Of.Foo, Assembly, Qualified Name Type Name" />
<add name = "bar"
type = "The.System.Type.Of.Bar, Assembly, Qualified Name Type Name" />
</MyMainSection>
我定义了以下代码:
using System.Configuration;
class MyMainSection : ConfigurationSection
{
/*I've provided custom implemenation.
Not including it here for the sake of brevity. */
[ConfigurationProperty("attributeForMainSection")]
public string AttributeForMyMainSection { get; set; }
[ConfigurationProperty("add")]
public AddElement TheAddElement { get; set; }
private class AddElement: ConfigurationElement
{
/* Implementation done */
}
}
这个属性应该TheAddElement
是IEnumerable<AddElement>
或者只是 AddElement
如果我想允许多个添加元素?
最佳答案
两者都不是,你会引入一个新的 ConfigurationCollectionElement相反,例如
部分
class MyMainSection : ConfigurationSection
{
[ConfigurationProperty("", IsRequired=true, IsDefaultCollection=true)]
public AddElementCollection Instances
{
get { return (AddElementCollection) this[""]; }
set { this[""] = value; }
}
}
收藏
public class AddElementCollection : ConfigurationElementCollection
{
protected override ConfigurationElement CreateNewElement()
{
return new AddElement();
}
protected override object GetElementKey(ConfigurationElement element) {
return ((AddElement) element).Name;
}
}
元素
private class AddElement: ConfigurationElement
{
[ConfigurationProperty("name", IsKey=true, IsRequired=true)]
public string Name
{
get { return (string) base["name"]; }
set { base["name"] = value;
}
...
}
关于c# - 包含子元素集合的配置元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13857362/