要使您的集合元素直接位于父元素(而不是子集合元素)中,您需要重新定义您的ConfigurationProperty
. 例如,假设我有一个集合元素,例如:
public class TestConfigurationElement : ConfigurationElement
{
[ConfigurationProperty("name", IsKey = true, IsRequired = true)]
public string Name
{
get { return (string)this["name"]; }
}
}
和一个集合,例如:
[ConfigurationCollection(typeof(TestConfigurationElement), AddItemName = "test")]
public class TestConfigurationElementCollection : ConfigurationElementCollection
{
protected override ConfigurationElement CreateNewElement()
{
return new TestConfigurationElement();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((TestConfigurationElement)element).Name;
}
}
我需要将父部分/元素定义为:
public class TestConfigurationSection : ConfigurationSection
{
[ConfigurationProperty("", IsDefaultCollection = true)]
public TestConfigurationElementCollection Tests
{
get { return (TestConfigurationElementCollection)this[""]; }
}
}
注意[ConfigurationProperty("", IsDefaultCollection = true)]
属性。给它一个空名称,并将其设置为默认集合允许我定义我的配置,如:
<testConfig>
<test name="One" />
<test name="Two" />
</testConfig>
代替:
<testConfig>
<tests>
<test name="One" />
<test name="Two" />
</tests>
</testConfig>