一般来说,我对 WPF 和 C# 非常陌生,使用 app.config 让我感到困惑。完成一些非常基本的事情感觉不必要地困难。我只想在我的应用程序中添加一些数据驱动的设置,并想使用 app.config。
经过一番研究,看起来“appSettings”很旧并且没有类型检查,并且“applicationSettings”似乎已被弃用(它甚至不在VS 2012的标准架构中)。所以,我现在正在尝试创建一个自定义配置部分。我根据示例编写了一个非常简单的示例,但它在启动期间抛出了 TypeInitializationException。我盯着代码看,但看不出有什么问题。
app.config 文件:
<configSections>
<section name="applicationConfig" type="MyApp.ApplicationConfig, MyApp"/>
</configSections>
<applicationConfig
UseLocalhost="true"
WebServer="http://www.someserver.com"
MachineId="999"/>
C#代码:
namespace MyApp
{
public class ApplicationConfig : ConfigurationSection
{
public ApplicationConfig()
{
}
public static ApplicationConfig GetConfig()
{
return (ApplicationConfig)System.Configuration.ConfigurationManager.GetSection("applicationConfig") ?? new ApplicationConfig();
}
[ConfigurationProperty("UseLocalhost", DefaultValue = false, IsRequired = false)]
public bool UseLocalhost
{
get { return (bool)this["UseLocalhost"]; }
set { this["UseLocalhost"] = value; }
}
[ConfigurationProperty("WebServer", IsRequired = true)]
public string WebServer
{
get { return (string)this["WebServer"]; }
set { this["WebServer"] = value; }
}
[ConfigurationProperty("MachineId", DefaultValue = 999, IsRequired = false)]
public int MachineId
{
get { return (int)this["MachineId"]; }
set { this["MachineId"] = value; }
}
}
}
谢谢您的帮助。