2008-10-15 60 views
11

我正在編寫一個可以使用幾個不同主題的頁面,並且我將在web.config中存儲有關每個主題的一些信息。將值存儲在web.config中 - appSettings或configSection - 哪種效率更高?

創建一個新的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(); 

回答

11

對於更復雜的配置設置,我會使用自定義配置節,明確規定,例如

<appMonitoring enabled="true" smtpServer="xxx"> 
    <alertRecipients> 
    <add name="me" email="[email protected]"/> 
    </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; 
10

會有效率方面沒有可測量的差異。

如果您只需要名稱/值對,則AppSettings非常棒。

對於任何更復雜的情況,值得創建一個自定義配置部分。

對於你提到的例子,我會使用appSettings。

6

性能沒有差別,因爲ConfigurationManager.AppSettings只是調用GetSection(「appSettings」)。如果您需要枚舉所有鍵,那麼自定義部分將比列舉所有appSettings並在鍵上尋找一些前綴更好,但除此之外,更容易粘貼到appSettings,除非您需要比NameValueCollection更復雜的東西。

+0

但讓我們說,我們不斷增加值appSettings和列表變得巨大。枚舉所有列表並找到需要的條目會不會影響性能?我相信那是什麼框架。它獲取appSettings部分,然後枚舉所有鍵值對以找到具有匹配鍵值的一個? – ItsZeus 2016-05-18 11:25:42

相關問題