通過泛型,將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