/// <summary>Sets the value.</summary> /// <param name="propertyInfo">The property info.</param> /// <param name="obj">The object to set the value on.</param> /// <param name="value">The value to set.</param> public static void SetValue(this PropertyInfo propertyInfo, object obj, string value) { var propertyType = propertyInfo.PropertyType; if (propertyType.IsEnum) { var enumValue = EnumExtensions.ToEnum(propertyType, value); propertyInfo.SetValue(obj, enumValue, null); return; } if (propertyType.IsNullableT()) { //If the proerty is nullable and the value is null or empty, do not set it. if (string.IsNullOrEmpty(value)) { return; } propertyType = Nullable.GetUnderlyingType(propertyType); } MethodInfo methodInfo = propertyType.GetMethod("TryParse", new Type[] { typeof(string), propertyType.MakeByRefType() }); if (methodInfo == null) { propertyInfo.SetValue(obj, value, null); return; } //If the value is nullable and it fails to parse, this will set the default value. object[] arguments = { value, null }; methodInfo.Invoke(null, arguments); propertyInfo.SetValue(obj, arguments[1], null); }
/// <summary>Parses a string and converts to an enumeration.</summary> /// <typeparam name="T">Type of enumeration to return.</typeparam> /// <param name="fieldValue">EnumMemberAttribute.Value string or enum.ToString().</param> /// <returns>Enumeration of the correct value.</returns> public static T ToEnum <T>(string fieldValue) where T : struct, IConvertible { return((T)(object)EnumExtensions.ToEnum(typeof(T), fieldValue)); }
/// <summary>Parses a string and converts to an enumeration.</summary> /// <typeparam name="T">Type of enumeration to return.</typeparam> /// <param name="fieldValue">String value.</param> /// <param name="defaultValue">Default value to use if the EnumMemberAttribute is not obtained.</param> /// <returns>Enumeration of the correct value.</returns> public static T ToEnum <T>(this string fieldValue, T defaultValue) where T : struct, IConvertible { return(EnumExtensions.ToEnum <T>(fieldValue, defaultValue)); }