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;
}
}