直接上代码:
public class MySection : ConfigurationSection
{
private const String collectionProertyName = ""; //如果 ConfigurationProperty 的某个实例为默认集合,则此实例的名称将被自动定义为一个空字符串
[ConfigurationProperty(collectionProertyName, Options = ConfigurationPropertyOptions.IsDefaultCollection)]
public MySettingsCollection MySettings
{
get
{
return (MySettingsCollection)base[collectionProertyName];
}
}
public static MySection Section
{
get
{
MySection section = ConfigurationManager.GetSection("mySettings") as MySection;
if ((section == null))
{
throw new ConfigurationErrorsException("配置定义错误");
}
return section;
}
}
}
public class MySettings : ConfigurationElement
{
[ConfigurationProperty("key", Options = ConfigurationPropertyOptions.IsKey | ConfigurationPropertyOptions.IsRequired)] //注意IsKey
public String Key
{
get { return (String)base["key"]; }
set { base["key"] = value; }
}
[ConfigurationProperty("value1")] //注意大小写
public Decimal Value1
{
get { return (Decimal)base["value1"]; }
set { base["value1"] = value; }
}
[ConfigurationProperty("value2")]
public Decimal Value2
{
get { return (Decimal)base["value2"]; }
set { base["value2"] = value; }
}
}
public class MySettingsCollection : ConfigurationElementCollection
{
protected override ConfigurationElement CreateNewElement()
{
return new MySettings();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((MySettings)element).Key; //这个Key的Options要写IsKey,见上
}
public MySettings this[String Key]
{
get { return (MySettings)BaseGet(Key); }
}
}
以上为代码,下面是配置:
<configuration>
<configSections>
<!--type="Study.SystemConfiratuion.MySection,Study"中Study.SystemConfiratuion.MySection指的是类;Study指的是程序集 -->
<section name="mySettings" type="Study.SystemConfiratuion.MySection,Study"/>
</configSections>
<mySettings>
<add key="test1" value1="11" value2="12"></add>
<add key="test2" value1="21" value2="22"></add>
</mySettings>
</configuration>
[Test] //测试
public void Test()
{
var settings = MySection.Section.MySettings;
Assert.AreEqual(11,settings["test1"].Value1);
Assert.AreEqual(12, settings["test1"].Value2);
Assert.AreEqual(21, settings["test2"].Value1);
Assert.AreEqual(22, settings["test2"].Value2);
}