public static string ConvertToString(object o) { if (o == null) { return(null); } if (o.GetType().GetTypeInfo().IsEnum) { // Try to convert the Enum value using the StringValue attribute. var enumType = o.GetType(); FieldInfo field = enumType.GetField(o.ToString()); StringValueAttribute attribute = field.GetCustomAttribute <StringValueAttribute>(); return(attribute != null ? attribute.Text : o.ToString()); } if (o is DateTime) { // Honor RFC3339. return(ConvertToRFC3339((DateTime)o)); } if (o is bool) { return(o.ToString().ToLowerInvariant()); } return(o.ToString()); }
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { if (value == null) { return(null); } Type enumType = value.GetType(); if (!CanConvertTo(context, destinationType) || !CanConvertFrom(context, enumType)) { return(base.ConvertTo(context, culture, value, destinationType)); } // Get the field in the enum. FieldInfo field = enumType.GetField(value.ToString()); // Check if this element has a StringValueAttribute. StringValueAttribute attribute = field.GetCustomAttribute <StringValueAttribute>(); // If it has an attribute, then return the specified text, otherwise use the default overload. return(attribute != null ? attribute.Text : value.ToString()); }
public void ConstructTest() { // Test parameter validation/ Assert.Throws<ArgumentNullException>(() => new StringValueAttribute(null)); // Test normal operation. var attribute = new StringValueAttribute("FooBar"); Assert.AreEqual("FooBar", attribute.Text); }
/// <summary> /// Tries to convert the specified object to a string. Uses custom type converters if available. /// Returns null for a null object. /// </summary> public static string ConvertToString(object o) { if (o == null) { return(null); } if (o.GetType().IsEnum) { // try to convert the Enum value using the StringValue attribute var enumType = o.GetType(); FieldInfo field = enumType.GetField(o.ToString()); StringValueAttribute attribute = field.GetCustomAttribute <StringValueAttribute>(); return(attribute != null ? attribute.Text : o.ToString()); } return(o.ToString()); }