【问题标题】:AppSettings fallback/default value?AppSettings 后备/默认值?
【发布时间】:2011-04-15 08:29:27
【问题描述】:

ASP.NET

对于我使用的每个 appSetting,我想指定一个值,如果在 appSettings 中找不到指定的键,将返回该值。我正要创建一个类来管理它,但我想这个功能可能已经在 .NET Framework 的某个地方了?

.NET 中是否有一个 NameValueCollection/Hash/etc-type 类可以让我指定一个键和一个备用/默认值——并返回键的值或指定的值?

如果有,我可以将 appSettings 放入该类型的对象中,然后再调用它(从不同的地方)。

【问题讨论】:

    标签: c# asp.net appsettings namevaluecollection fallbackvalue


    【解决方案1】:

    这就是我的工作。

    WebConfigurationManager.AppSettings["MyValue"] ?? "SomeDefault")
    

    对于布尔值和其他非字符串类型...

    bool.Parse(WebConfigurationManager.AppSettings["MyBoolean"] ?? "false")
    

    【讨论】:

      【解决方案2】:

      我认为 .NET 中没有内置任何东西可以提供您正在寻找的功能。

      您可以创建一个基于 Dictionary<TKey, TValue> 的类,该类提供 TryGetValue 的重载以及默认值的附加参数,例如:

      public class MyAppSettings<TKey, TValue> : Dictionary<TKey, TValue>
      {
          public void TryGetValue(TKey key, out TValue value, TValue defaultValue)
          {
              if (!this.TryGetValue(key, out value))
              {
                  value = defaultValue;
              }
          }
      }
      

      您可能会使用strings 而不是保持通用。

      如果可以的话,还有来自 Silverlight 和 WPF 世界的 DependencyObject

      当然,最简单的方法是使用NameValueCollection

      string value = string.IsNullOrEmpty(appSettings[key]) 
          ? defaultValue 
          : appSettings[key];
      

      key 可以是字符串索引器上的null。但我知道在多个地方这样做很痛苦。

      【讨论】:

      • 我提供了一种扩展方法来执行此操作,其中包括 TypeConverstion:stackoverflow.com/a/34053423/375727。显然不适合 OP,因为这篇文章已有 5 年历史,但像我这样没有在这里找到答案的未来谷歌人。
      【解决方案3】:

      您可以制作自定义配置部分并使用 DefaultValue 属性提供默认值。 here 提供了相关说明。

      【讨论】:

      • 另一个很好的答案表明我问我的问题有多糟糕。我可能需要根据调用者(和/或仅在运行时确定的值)指定不同的回退/默认值。我不应该提到 appSettings,因为我真的需要一个 NameValueCollection 类型的对象,它可以让我指定在找不到键时要返回的值。
      【解决方案4】:

      我认为 C:\%WIN%\Microsoft.NET 下的 machine.config 会这样做。将该文件的键添加为默认值。

      http://msdn.microsoft.com/en-us/library/ms228154.aspx

      【讨论】:

      • Machine.config 会给我一个后备值,但我不能在代码中指定它?那正确吗?我正在寻找可以让我在代码中指定当 appSettings 没有我指定的键时应该返回的值的东西。我提到了 appSettings,但这个问题与任何 NameValueCollection/Hash 一样多,尤其是关于 appSettings(或 *.config)。
      【解决方案5】:

      您可以围绕 ConfigurationManager 构建逻辑,以获得一种类型化的方式来检索您的应用设置值。这里使用 TypeDescriptor 来转换值。

      /// <summary>
      /// Utility methods for ConfigurationManager
      /// </summary>
      public static class ConfigurationManagerWrapper
      {
          /// <summary>
          /// Use this extension method to get a strongly typed app setting from the configuration file.
          /// Returns app setting in configuration file if key found and tries to convert the value to a specified type. In case this fails, the fallback value
          /// or if NOT specified - default value - of the app setting is returned
          /// </summary>
          public static T GetAppsetting<T>(string appsettingKey, T fallback = default(T))
          {
              string val = ConfigurationManager.AppSettings[appsettingKey] ?? "";
              if (!string.IsNullOrEmpty(val))
              {
                  try
                  {
                      Type typeDefault = typeof(T);
                      var converter = TypeDescriptor.GetConverter(typeof(T));
                      return converter.CanConvertFrom(typeof(string)) ? (T)converter.ConvertFrom(val) : fallback;
                  }
                  catch (Exception err)
                  {
                      Console.WriteLine(err); //Swallow exception
                      return fallback;
                  }
              }
              return fallback;
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-07-03
        • 2016-02-27
        • 1970-01-01
        • 1970-01-01
        • 2020-01-14
        • 2016-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多