c# – 如何从App.config中读取此自定义配置?
发布时间:2020-12-15 04:00:27 所属栏目:百科 来源:网络整理
导读:如何从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="roo
如何从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> (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |