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

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;
        }
复制代码

 

作者:Chuck Lu    GitHub    
posted @   ChuckLu  阅读(4113)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2018-05-10 git的基本操作流程
2018-05-10 XHR ajax
2018-05-10 js的类库
2017-05-10 Virtual Directory in IIS
2017-05-10 System Databases in SQL Server
2017-05-10 win7 一个电脑接入多个显示器
2016-05-10 从vs中删除自带的Microsoft Git Provider
点击右上角即可分享
微信分享提示