首页 > 其他 > 详细

通过泛型,将string转换为指定类型

时间:2019-05-10 18:07:40      阅读:438      评论:0      收藏:0      [点我收藏+]

Generic TryParse

You should use the TypeDescriptor class:

public static T Convert<T>(this string input)
{
    try
    {
        var converter = TypeDescriptor.GetConverter(typeof(T));
        if(converter != null)
        {
            // Cast ConvertFromString(string text) : object to (T)
            return (T)converter.ConvertFromString(input);
        }
        return default(T);
    }
    catch (NotSupportedException)
    {
        return default(T);
    }
}

自己的版本

public static T GetAppSetting<T>(string key)
        {
            T result;
            var value = ConfigurationManager.AppSettings[key];
            if (string.IsNullOrEmpty(value))
            {
                throw new ConfigurationErrorsException($"Can not find app setting by key: {key}");
            }

            Type type = typeof(T);
            var converter = TypeDescriptor.GetConverter(type);
            if (converter == null)
            {
                throw new ObjectNotFoundException($"Can not get the converter for Type: {type.FullName}");
            }

            try
            {
                var obj = converter.ConvertFromString(value);
                result = (T) obj;
            }
            catch (Exception ex)
            {
                throw new ConfigurationErrorsException(
                    $"Can not read the app setting by key: {key} with Type {type.FullName}", ex);
            }

            return result;
        }

 

通过泛型,将string转换为指定类型

原文:https://www.cnblogs.com/chucklu/p/10845709.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!