12

我正在编写一个可以使用几个不同主题的页面,并且我将在 web.config 中存储有关每个主题的一些信息。

创建一个新的sectionGroup并将所有内容存储在一起,还是将所有内容放在appSettings中更有效?

configSection解决方案

<configSections>
    <sectionGroup name="SchedulerPage">
        <section name="Providers" type="System.Configuration.NameValueSectionHandler"/>
        <section name="Themes" type="System.Configuration.NameValueSectionHandler"/>
    </sectionGroup>
</configSections>
<SchedulerPage>
    <Themes>
        <add key="PI" value="PISchedulerForm"/>
        <add key="UB" value="UBSchedulerForm"/>
    </Themes>
</SchedulerPage>

要访问 configSection 中的值,我使用以下代码:

    NameValueCollection themes = ConfigurationManager.GetSection("SchedulerPage/Themes") as NameValueCollection;
    String SchedulerTheme = themes["UB"];

appSettings 解决方案

<appSettings>
    <add key="PITheme" value="PISchedulerForm"/>
    <add key="UBTheme" value="UBSchedulerForm"/>
</appSettings>

要访问 appSettings 中的值,我正在使用此代码

    String SchedulerTheme = ConfigurationManager.AppSettings["UBSchedulerForm"].ToString();
4

3 回答 3

12

对于更复杂的配置设置,我会使用一个自定义配置部分,它清楚地定义了每个部分的角色,例如

<appMonitoring enabled="true" smtpServer="xxx">
  <alertRecipients>
    <add name="me" email="me@me.com"/>
  </alertRecipient>
</appMonitoring>

在您的配置类中,您可以使用类似的方式公开您的属性

public class MonitoringConfig : ConfigurationSection
{
  [ConfigurationProperty("smtp", IsRequired = true)]
  public string Smtp
  {
    get { return this["smtp"] as string; }
  }
  public static MonitoringConfig GetConfig()
  {
    return ConfigurationManager.GetSection("appMonitoring") as MonitoringConfig
  }
}

然后,您可以通过以下方式从您的代码中访问配置属性

string smtp = MonitoringConfig.GetConfig().Smtp;
于 2008-10-15T13:43:00.270 回答
10

在效率方面不会有可衡量的差异。

如果您只需要名称/值对,AppSettings 就很棒。

对于更复杂的事情,值得创建一个自定义配置部分。

对于您提到的示例,我将使用 appSettings。

于 2008-10-15T13:31:45.520 回答
6

性能不会有任何差异,因为 ConfigurationManager.AppSettings 无论如何都只是调用 GetSection("appSettings") 。如果您需要枚举所有键,那么自定义部分将比枚举所有 appSettings 并在键上查找一些前缀更好,但否则坚持使用 appSettings 会更容易,除非您需要比 NameValueCollection 更复杂的东西。

于 2008-10-15T13:48:07.810 回答