背景: 尝试按照以下示例在 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 section = (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];