ConfigurationElementCollection.ElementName详解

ConfigurationElementCollection.ElementName属性在MSDN的解释是这样:

Gets the name used to identify this collection of elements in the configuration file when overridden in a derived class.

获取在派生的类中重写时用于标识配置文件中此元素集合的名称。

接着没有任何代码示例……根本看不懂了啊!!!

后经过研究发现功能类似ConfigurationElementCollection.AddElementName属性(这个得在ConfigurationCollectionAttribute中设置),只不过他是只针对BasicMap和BasicMapAlternate的。从名字上也可以看出来:AddElementName,RemoveElementName和ClearElementName是为AddRemoveClearMap服务的。

比如:下面这个简单的不能再简单的ConfigurationElementCollection类的代码:

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Configuration; namespace Mgen { class Program { static void Main() { var mysec = (MySection)ConfigurationManager.GetSection("mysec"); foreach (MyElemenet ele in mysec.MyElements) Console.WriteLine(ele.Id); } } class MySection : ConfigurationSection { [ConfigurationProperty("", IsDefaultCollection = true)] public MyCollec MyElements { get { return (MyCollec)this[""]; } } } [ConfigurationCollection(typeof(MyElemenet), AddItemName = "ele")] class MyCollec : ConfigurationElementCollection { protected override ConfigurationElement CreateNewElement() { return new MyElemenet(); } protected override object GetElementKey(ConfigurationElement element) { return ((MyElemenet)element).Id; } } class MyElemenet : ConfigurationElement { [ConfigurationProperty("id", IsKey = true)] public int Id { get { return (int)this["id"]; } } [ConfigurationProperty("name")] public string Name { get { return (string)this["name"]; } } } }

由于设置了AddElementName,因此在配置文件上我们可以这样写:

<?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="mysec" type="Mgen.MySection, Mgen"/> </configSections> <mysec> <ele id="23" name="mgen" /> <ele id="34" name="another" /> </mysec> </configuration>

输出:23和34

此时ConfigurationElementCollection的类型是默认的AddRemoveClearMap,可当ConfigurationElementCollection的类型被改成BasicMap或BasicMapAlternate后,AddElementName就不好使了,会有异常抛出(无法识别的元素'ele')。

此时不用设置AddElementName,直接改写ElementName属性就可以了。

[ConfigurationCollection(typeof(MyElemenet))] class MyCollec : ConfigurationElementCollection { public override ConfigurationElementCollectionType CollectionType { get { return ConfigurationElementCollectionType.BasicMap; } } protected override string ElementName { get { return "ele"; } } protected override ConfigurationElement CreateNewElement() { return new MyElemenet(); } protected override object GetElementKey(ConfigurationElement element) { return ((MyElemenet)element).Id; } }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值