System.InvalidCastException 在 app.config 中添加自定义部分后

System.InvalidCastException after adding customize section in app.config

我想创建一个简单的部分而不需要自己编写任何 class,我已经阅读了其他帖子并尝试构建我自己的部分但是当我尝试获取时它抛出异常 System.InvalidCastException我的部分。谁能告诉我如何解决它?谢谢!

异常消息:

'System.InvalidCastException' 类型的未处理异常发生在 HttpServer.exe

附加信息:无法将类型 'System.Configuration.KeyValueInternalCollection' 的对象转换为类型 'System.Configuration.AppSettingsSection'。

App.config:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="extensions" type="System.Configuration.AppSettingsSection" />
  </configSections>

  <extensions>
    <add key=".gif" value="image/gif"/>
    <add key=".png" value="image/png"/>
    <add key=".jpg" value="image/jpeg"/>
  </extensions>

  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
  </startup>
</configuration>

C#代码:

AppSettingsSection section = (AppSettingsSection)ConfigurationManager.GetSection("extensions");
Console.WriteLine(section.Settings[".gif"].Value.ToString());

将 System.Configuration.AppSettingsSection 更改为 System.Configuration.NameValueSectionHandler 并通过以下方式获取值 System.Collections.Specialized.NameValueCollection