我试图从应用程序的配置文件中获取项目的集合。一切看起来不错,但我总是取0元(不考虑,我把配置文件上...)从App.config文件读取集合
我的代码是:
using System.Configuration;
namespace CustomSettingConfiguration
{
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("Tests", IsDefaultCollection = true)]
public TestConfigurationElementCollection Tests
{
get { return (TestConfigurationElementCollection)this["Tests"]; }
}
}
}
和配置文件:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="TestConfigurationSection" type="CustomSettingConfiguration.TestConfigurationSection" />
</configSections>
<TestConfigurationSection>
<Tests>
<test name="One" />
<test name="Two" />
</Tests>
</TestConfigurationSection>
</configuration>
使用它:
TestConfigurationSection a = new TestConfigurationSection();
var tests = a.Tests;
任何想法??
在此先感谢
感谢您的回应,但它并没有工作。 – 2011-12-27 21:48:04
是的,我的错,但是我找到了正确的答案,很快就会发布 – 2011-12-27 21:56:06
答案已更新,请查看 – 2011-12-28 09:42:09