上記のJay Walkerの回答に基づいて、これはインデックス作成を実行する機能を追加する完全に機能する例です。
<configuration>
<configSections>
<section name="registerCompanies"
type="My.MyConfigSection, My.Assembly" />
</configSections>
<registerCompanies>
<add name="Tata Motors" code="Tata"/>
<add name="Honda Motors" code="Honda"/>
</registerCompanies>
</configuration>
折りたたまれたコレクションでカスタム構成セクションを実装するためのサンプルコードは次のとおりです
using System.Configuration;
using System.Linq;
namespace My
{
public class MyConfigSection : ConfigurationSection
{
[ConfigurationProperty("", IsRequired = true, IsDefaultCollection = true)]
public MyConfigInstanceCollection Instances
{
get { return (MyConfigInstanceCollection)this[""]; }
set { this[""] = value; }
}
}
public class MyConfigInstanceCollection : ConfigurationElementCollection
{
protected override ConfigurationElement CreateNewElement()
{
return new MyConfigInstanceElement();
}
protected override object GetElementKey(ConfigurationElement element)
{
//set to whatever Element Property you want to use for a key
return ((MyConfigInstanceElement)element).Name;
}
public new MyConfigInstanceElement this[string elementName]
{
get
{
return this.OfType<MyConfigInstanceElement>().FirstOrDefault(item => item.Name == elementName);
}
}
}
public class MyConfigInstanceElement : ConfigurationElement
{
//Make sure to set IsKey=true for property exposed as the GetElementKey above
[ConfigurationProperty("name", IsKey = true, IsRequired = true)]
public string Name
{
get { return (string)base["name"]; }
set { base["name"] = value; }
}
[ConfigurationProperty("code", IsRequired = true)]
public string Code
{
get { return (string)base["code"]; }
set { base["code"] = value; }
}
}
}
以下は、コードから構成情報にアクセスする方法の例です。
MyConfigSection config =
ConfigurationManager.GetSection("registerCompanies") as MyConfigSection;
Console.WriteLine(config.Instances["Honda Motors"].Code);
foreach (MyConfigInstanceElement e in config.Instances)
{
Console.WriteLine("Name: {0}, Code: {1}", e.Name, e.Code);
}