如何从App.config中读取此自定义配置?
<root name="myRoot" type="rootType"> <element name="myName" type="myType" /> <element name="hisName" type="hisType" /> <element name="yourName" type="yourType" /> </root>
而不是这样:
<root name="myRoot" type="rootType"> <elements> <element name="myName" type="myType" /> <element name="hisName" type="hisType" /> <element name="yourName" type="yourType" /> </elements> </root>
解决方法
要使您的集合元素直接位于父元素(而不是子集合元素)中,则需要重新定义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>