2011-03-25 33 views
3
<appSettings> 
     <!-- Settings file for website! --> 
     <add key="DefaultCookieExpiryMins" value="30" /> 
    </appSettings> 

爲什麼我必須將所有內容都設置爲字符串?爲什麼我不能在int中使用不同的數據類型來幫助我停止投射所有內容?ASP.net爲什麼只有應用程序設置字符串?

+1

寫一個包裝類,所以你只需要投一次 – citronas 2011-03-25 17:37:21

+1

文本文件只包含字符串。你想與衆不同?要麼你將它轉換爲代碼中的'int',要麼你猜我會在web.config中添加類似於'type =「int」'的東西?但是由於沒有任何東西可以阻止你將任何你想要的東西輸入到文本文件中,即使你可以添加一個數據類型到一個設置中,它似乎也是毫無意義的。你仍然可能有不好的數據。如果您在從配置文件獲取數據時未驗證數據,它仍然會在某處出現故障。 – 2011-03-25 20:05:36

回答

6

這就是爲什麼我更喜歡自定義配置部分,而不僅僅是將鍵/值對放在appSettings中。有關如何製作自己的配置部分的更多信息,請參閱this MSDN article。一旦您擁有了自己的配置部分課程,您應該能夠以任何您想要的數據類型訪問您的設置。

0

我只是使用泛型來處理這樣的事情。

public static T GetConfigurationValue<T>(string keyName) 
     { 
      if (System.Configuration.ConfigurationManager.AppSettings[keyName] != null) 
      { 
       T result; 
       try 
       { 
        result = (T)Convert.ChangeType(System.Configuration.ConfigurationManager.AppSettings[keyName], typeof(T)); 
       } 
       catch 
       { 
        return default(T); 
       } 

       return result; 
      } 

      throw new ArgumentException("A key with the name " + keyName + " does not exist in the current configuration.", keyName); 
     } 

用法:GetConfigurationValue<int>("DefaultCookieExpiryMins");

相關問題