0

一般来说,我对 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; }
        }
    }
}

谢谢您的帮助。

4

2 回答 2

0

我过去发现,您不能在配置对象的同一程序集中拥有自定义配置对象。尝试将对象放入单独的程序集中,在项目中引用该新程序集,更新 .config 文件中自定义对象的程序集,然后从那里开始

于 2013-03-24T13:08:21.627 回答
0

看起来异常是由其他一些代码引发的 - 而不是您引用的配置节类。TypeInitializerException 由静态构造函数或静态字段初始值设定项引发,您的代码都没有。你如何调用 GetConfig()?底线是:查看代码中的其他地方,您的部分类和配置文件 XML 似乎没问题。

于 2013-03-24T01:21:57.643 回答