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; }