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 を列挙してキーのプレフィックスを探すよりもカスタム セクションの方が便利ですが、それ以外の場合は、NameValueCollection よりも複雑なものが必要でない限り、appSettings に固執する方が簡単です。

于 2008-10-15T13:48:07.810 に答える