ConfigurationManager & Static Class

前端 未结 3 1478
故里飘歌
故里飘歌 2021-01-03 03:06

I would like to use ConfigurationManager to access some string values from a static class. However, I need to handle specifically the absence of a valu

3条回答
  •  执笔经年
    2021-01-03 03:43

    This just came up in a code review. The answers provided are great for strings. But they don't work for an int or a double, etc... Today, I needed to do this for a retry count and it needs to be an int.

    So here is an answer for those who want Type conversion included.

    Use this extension method:

    using System.Collections.Specialized;
    using System.ComponentModel;
    
    namespace Rhyous.Config.Extensions
    {
        public static class NameValueCollectionExtensions
        {
            public static T Get(this NameValueCollection collection, string key, T defaultValue)
            {
                var value = collection[key];
                var converter = TypeDescriptor.GetConverter(typeof(T));
                if (string.IsNullOrWhiteSpace(value) || !converter.IsValid(value))
                {
                    return defaultValue;
                }
    
                return (T)(converter.ConvertFromInvariantString(value));
            }
        }
    }
    

    I also have unit tests for it, which you can find here: http://www.rhyous.com/2015/12/02/how-to-easily-access-a-web-config-appsettings-value-with-a-type-and-a-default-value

    Hope that helps the next guy.

提交回复
热议问题