TryGetValueFromConfig:读取配置信息时防止出错

using System;
using System.Configuration;
using System.Diagnostics;
using System.Runtime.CompilerServices;

public sealed class ConfigHelper
{
    private static readonly ConfigHelper _instance = null;

    #region Constructors
    static ConfigHelper()
    {
        _instance = new ConfigHelper();
    }

    private ConfigHelper() { }
    #endregion

    public static ConfigHelper Instance { get { return _instance; } }

    /// 
    /// 转换Appsetting节点信息为指定类型
    /// 
    /// 类型
    /// 需要转换的类型
    /// 类型默认值
    /// AppSetting节点name
    /// 节点类型
    public T TryGetValueFromConfig(Func parseFunc, Func defaultTValueFunc, [CallerMemberName]string key = "")
    {
        try
        {
            var node = ConfigurationManager.AppSettings[key];
            return !string.IsNullOrWhiteSpace(node) ? parseFunc(node) : defaultTValueFunc();
        }
        catch (Exception ex)
        {
            Trace.Write(ex.Message);
            return default(T);
        }
    }

}

你可能感兴趣的:(TryGetValueFromConfig:读取配置信息时防止出错)