【问题标题】:ASP.net why is application settings string only?ASP.net 为什么只有应用程序设置字符串?
【发布时间】:2011-03-25 17:25:06
【问题描述】:
    <appSettings>
        <!-- Settings file for website! -->
        <add key="DefaultCookieExpiryMins" value="30" />
    </appSettings>

为什么我必须将所有内容都设置为字符串?为什么我不能在其中使用不同的数据类型(例如 int)来帮助我不必强制转换所有内容?

【问题讨论】:

  • 写一个包装类,所以只需要转换一次
  • 文本文件只包含字符串。你想要什么与众不同?要么您将其转换为代码中的int,或者您想将type="int" 之类的内容添加到web.config?但是,由于没有什么可以阻止您在文本文件中输入您想要的任何内容,即使您可以将数据类型添加到设置中,这似乎也毫无意义。你仍然可以有错误的数据。如果您在从配置文件中获取数据时不验证数据,它仍然会在某处中断。

标签: asp.net web-config application-settings


【解决方案1】:

这就是为什么我更喜欢自定义配置部分而不是仅仅将键/值对放在 appSettings 中。有关如何制作自己的配置部分的更多信息,请参阅this MSDN article。一旦你有了自己的配置节类,你应该能够以任何你喜欢的数据类型访问你的设置。

【讨论】:

    【解决方案2】:

    我只是在这样的事情上使用泛型。

    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&lt;int&gt;("DefaultCookieExpiryMins");

    【讨论】:

      猜你喜欢
      • 2011-03-11
      • 1970-01-01
      • 2010-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-06
      • 2011-04-19
      • 1970-01-01
      相关资源
      最近更新 更多