我想创建一个简单的部分而不用自己编写任何类,我已经阅读了其他帖子并尝试构建我自己的部分但是当我尝试获取我的部分时它抛出了 System.InvalidCastException 异常。谁能告诉我如何解决它?谢谢!
异常信息:
HttpServer.exe 中发生类型为“System.InvalidCastException”的未处理异常
附加信息:无法将“System.Configuration.KeyValueInternalCollection”类型的对象转换为类型“System.Configuration.AppSettingsSection”。
应用程序配置:
<?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
关于c# - 在 app.config 中添加自定义部分后出现 System.InvalidCastException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39283319/