背景: 次の例に従って app.config にリストを実装しようとしています:
- http://jopinblog.wordpress.com/2007/04/20/custom-configurationsections-in-net-20-config-files/
- http://social.msdn.microsoft.com/Forums/en/csharpgeneral/thread/0f3557ee-16bd-4a36-a4f3-00efbeae9b0d
- 「追加」要素の単純なリストを含むカスタム app.config セクション
- app.config のカスタム構成 - セクションのコレクション?
目標: このエラーを解決して、これを機能させたいと考えています。
エラー:
要素 'lookupMapping' を認識できません。(C: ...75行目)
以下のデバッグ中にこの行で生成されたエラー:
LookupMappingsConfigSection セクション = (LookupMappingsConfigSection)config.Sections["lookupMappings"];
app.config スニペット:
<configuration>
<configSections>
<section name="lookupMappings" type="System.Configuration.AppSettingsSection, System.Configuration, Version=4.0.30319.1, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
</configSections>
<lookupMappings>
<lookupMapping name="One" lookupName="foo" />
<lookupMapping name="Two" lookupName="foo" />
<lookupMapping name="Three" lookupName="foo" />
<lookupMapping name="Four" lookupName="foo" />
</lookupMappings>
</configuration>
クラス:
public class LookupMappingsInstanceElement : ConfigurationElement
{
[ConfigurationProperty("name", IsRequired = true)]
public string Name
{
get { return (string)base["name"]; }
set { base["name"] = value; }
}
[ConfigurationProperty("lookupName", IsRequired = true)]
public string LookupName
{
get { return (string)base["lookupName"]; }
set { base["lookupName"] = value; }
}
}
public class LookupMappingsConfigSection: ConfigurationSection
{
[ConfigurationProperty("lookupMappings", IsDefaultCollection = true, IsRequired = true)]
[ConfigurationCollection(typeof(LookupMappingsConfigCollection), AddItemName = "lookupMapping")]
public LookupMappingsConfigCollection Instances
{
get { return (LookupMappingsConfigCollection) this[""]; }
set { this[""] = value; }
}
}
public class LookupMappingsConfigCollection : ConfigurationElementCollection
{
protected override ConfigurationElement CreateNewElement()
{
return new LookupMappingsInstanceElement();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((LookupMappingsInstanceElement) element).Name;
}
public LookupMappingsInstanceElement this[int idx]
{
get { return (LookupMappingsInstanceElement)BaseGet(idx); }
}
public override ConfigurationElementCollectionType CollectionType
{
get { return ConfigurationElementCollectionType.BasicMap; }
}
protected override string ElementName
{
get { return "lookupMapping"; }
}
}
実装 c#:
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
LookupMappingsConfigSection section = (LookupMappingsConfigSection)config.Sections["lookupMappings"]; // <--ERROR ON THIS LINE
LookupMappingsInstanceElement entry1 = section.Instances[0];
LookupMappingsInstanceElement entry2 = section.Instances[1];