通过泛型,将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;
        }

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM