private T ConvertValue <T>(string str) { Type type = typeof(T); if (type == typeof(string)) { return((T)(object)str); } else if (type == typeof(decimal)) { return((T)(object)convertToDecimal(str)); } else if (typeof(Enum).IsAssignableFrom(type)) { return((T)MwsUtil.GetEnumValue(type, str)); } else if (typeof(IConvertible).IsAssignableFrom(type)) { return((T)Convert.ChangeType(str, type, CultureInfo.InvariantCulture)); } else if (Nullable.GetUnderlyingType(type) != null) { return(convertNullableType <T>(str)); } else { throw new InvalidDataException("Unsupported type for conversion from string: " + type.FullName); } }
private T ConvertValue <T>(string str) { Type type = typeof(T); if (type == typeof(string)) { return((T)(object)str); } else if (typeof(Enum).IsAssignableFrom(type)) { return((T)MwsUtil.GetEnumValue(type, str)); } else if (typeof(IConvertible).IsAssignableFrom(type)) { return((T)Convert.ChangeType(str, type, CultureInfo.InvariantCulture)); } else if (Nullable.GetUnderlyingType(type) != null) { // Nullable types don't pass through Convert correctly if (String.IsNullOrEmpty(str)) { return(default(T)); } else { // First, get the type that is nullable Type valueType = Nullable.GetUnderlyingType(type); // Recurse using the actual value type: ConvertValue<valueType> (must use reflection since we are generic) MethodInfo recursiveMethod = this.GetType().GetMethod("ConvertValue", BindingFlags.NonPublic | BindingFlags.Instance); var value = recursiveMethod.MakeGenericMethod(valueType).Invoke(this, new object[] { str }); // Return a new Nullable<valueType> (which is T) using the value we converted return((T)Activator.CreateInstance(type, new object[] { value })); } } else { throw new InvalidDataException("Unsupported type for conversion from string: " + type.FullName); } }