我想要app.Config中配置部分中存储的load int值。 这是我的app.Config文件:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
<configSections>
<section name="MySection" type="ConsoleApplication2.MySectionSection, ConsoleApplication2" />
</configSections>
<MySection>
<Add key="DefaultCapacity" value="15"/>
</MySection>
</configuration>
这是我的配置部分类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
public sealed class MySection
{
private static MySectionSection _config;
static MySection()
{
_config = ((MySectionSection)(global::System.Configuration.ConfigurationManager.GetSection("MySection")));
}
private MySection()
{
}
public static MySectionSection Config
{
get
{
return _config;
}
}
}
public sealed partial class MySectionSection : System.Configuration.ConfigurationSection
{
[System.Configuration.ConfigurationPropertyAttribute("Add")]
public AddElement Add
{
get
{
return ((AddElement)(this["Add"]));
}
}
public sealed partial class AddElement : System.Configuration.ConfigurationElement
{
[System.Configuration.ConfigurationPropertyAttribute("key", IsRequired = true)]
public string Key
{
get
{
return ((string)(this["key"]));
}
set
{
this["key"] = value;
}
}
[System.Configuration.ConfigurationPropertyAttribute("value", IsRequired = true)]
public long Value
{
get
{
return ((long)(this["value"]));
}
set
{
this["value"] = value;
}
}
}
}
}
但是当我尝试使用这样的代码来获取我的cofiguration部分时,我得到了异常
System.InvalidCastException。无法允许对象类型 键入“System.Configuration.DefaultSection” “ConsoleApplication2.MySectionSection
Configuration cfg = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var mn =(MySectionSection)cfg.GetSection("MySection"); //there is exception