代码之家  ›  专栏  ›  技术社区  ›  lance

AppSettings回退/默认值?

  •  3
  • lance  · 技术社区  · 14 年前

    在.NET中是否有一个NameValueCollection/Hash/etc类型类允许我指定一个键和一个fallback/default值,并返回键的值或指定的值?

    5 回复  |  直到 14 年前
        1
  •  2
  •   Heretic Monkey goproxy.dev    14 年前

    我不相信有任何内置的.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;
            }
        }
    }
    

    你也许可以逃脱惩罚 string 而不是保持通用。

    还有 DependencyObject

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

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

    key 可以是 null 在字符串索引器上。但我明白在多个地方这么做很痛苦。

        2
  •  2
  •   Carter Medlin    7 年前

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

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

    bool.Parse(WebConfigurationManager.AppSettings["MyBoolean"] ?? "false")
    
        3
  •  1
  •   Richard Anthony Hein    14 年前

    您可以创建一个自定义配置节,并使用DefaultValue属性提供默认值。可提供相关说明 here

        4
  •  0
  •   Dave Swersky    14 年前

    我认为机器配置C下:\%WIN%\微软.NET我会的。将键作为默认值添加到该文件中。

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

        5
  •  0
  •   Tore Aurstad    6 年前

    您可以围绕ConfigurationManager构建逻辑,以获取检索应用程序设置值的类型化方法。使用here TypeDescriptor转换值。

    /// ///ConfigurationManager的实用方法 /// {

        /// <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>
        /// <typeparam name="T"></typeparam>
        /// <param name="appsettingKey"></param>
        /// <param name="fallback"></param>
        /// <returns></returns>
        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;
        }
    
    }
    

    }