ConfigurationManager和静态类

Use*_*ser 5 .net c# static

我想用来ConfigurationManager静态类访问一些字符串值.但是,我需要特别处理缺少值或空值的存在.现在我正在使用类型初始化器,比如

private static readonly string someStr = ConfigurationManager.AppSettings["abc"];
Run Code Online (Sandbox Code Playgroud)

做这个工作.但是,如果App.config执行中不存在键"abc"的字符串,则可以继续使用null引用代替someStr.那么,什么是在初始化时验证此值的最佳方法?一个静态构造函数,我在其中初始化值然后检查有效性?我听说要避免使用静态构造函数,并尽可能用类型初始化程序替换.

jan*_*ani 7

我正在使用这样的东西:

public static readonly string someStr  = 
        ConfigurationManager.AppSettings["abc"] ?? "default value";
Run Code Online (Sandbox Code Playgroud)

或者处理空字符串:

public static readonly string someStr = 
           !String.IsNullOrEmpty(ConfigurationManager.AppSettings["abc"]) ? 
                             ConfigurationManager.AppSettings["abc"] : "default value";
Run Code Online (Sandbox Code Playgroud)


Rhy*_*ous 5

这只是在代码审查中出现的。提供的答案对于字符串来说非常有用。但它们不适用于 int 或 double 等...今天,我需要为重试计数执行此操作,并且它需要是 int。

因此,对于那些想要包含类型转换的人来说,这是一个答案。

使用这个扩展方法:

using System.Collections.Specialized;
using System.ComponentModel;

namespace Rhyous.Config.Extensions
{
    public static class NameValueCollectionExtensions
    {
        public static T Get<T>(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));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我也有它的单元测试,您可以在这里找到:http ://www.rhyous.com/2015/12/02/how-to-easily-access-a-web-config-appsettings-value-with-类型和默认值

希望对下一个人有所帮助。