65.9K
CodeProject 正在变化。 阅读更多。
Home

配置助手

starIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIconemptyStarIcon

1.72/5 (8投票s)

2004年6月29日

viewsIcon

34345

downloadIcon

376

简化了对 appSettings 下定义的键的使用。

引言

帮助使用位于 <appSettings> 下的键值,无论是在 web.config 中还是在 YourApp.exe.config 中。

背景

要访问应用程序设置,我们都使用过 web.config。 在开发 Web 项目时,我尝试将大部分变量(我认为需要随着时间推移进行更改的变量)保存在 web.config 文件中。 这样,未来的更改不需要重新编译代码。 例如,如果您有 cookie 超时或正在使用 webservice,您可能会编写以下代码从 web.config 访问键:

// accessing cookie time out

int cookieTimeOut =  40  ; // 40 mintues, default value

// to avoid exception if key not defined

if( System.Configuration.ConfigurationSettings.AppSettings["CookieTimeOut"] != 
                                               null )
{
    cookieTimout = Int32.Parse( 
      System.Configuration.ConfigurationSettings.AppSettings["CookieTimeOut"] ) ;
}

因此,如上所示,您需要编写一个 if 语句并使用 Int32 来解析整数。 如果您需要获取 doublestringbool 来自 <appSettings>,则此代码需要更改。 让我们使用这个类来看看它将如何获取值。

使用代码

using vs.helpers // namespace for ConfigHelper class


int cookieTimeOut = ConfigHelper.GetInt32("CookieTimeOut", 40); // for integer


// for other types of values you can use one of the following also

string connString = ConfigHelper.GetString("ConnString", 
   "your default connection string"); 
double currencyUnit = ConfigHelper.GetDouble("CurrencyUnit", 1.5);
bool persistantCookie = ConfigHelper.GetBoolean("PersistantCookie", false);

它减少了代码中的一些 if 语句,并使其更具可读性。 您不必使用冗长的语句 ( System.Configuration.ConfigurationSettings.AppSettings["key"] ) 并且无需进行值解析。

© . All rights reserved.