要使您的集合元素直接位于父元素中(而不是子集合元素),您需要重新定义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>