GenericEnumConverter
Converts between a string and an enumeration type.
using System.ComponentModel;
using System.Globalization;
namespace System.Configuration
{
public sealed class GenericEnumConverter : ConfigurationConverterBase
{
private readonly Type _enumType;
public GenericEnumConverter(Type typeEnum)
{
if (typeEnum == (Type)null)
throw new ArgumentNullException("typeEnum");
_enumType = typeEnum;
}
public override object ConvertTo(ITypeDescriptorContext ctx, CultureInfo ci, object value, Type type)
{
return value.ToString();
}
public override object ConvertFrom(ITypeDescriptorContext ctx, CultureInfo ci, object data)
{
string text = data as string;
if (text != null && text.Length > 0 && !char.IsDigit(text[0]) && text[0] != '-' && text[0] != '+' && !char.IsWhiteSpace(text[0]) && !char.IsWhiteSpace(text[text.Length - 1]))
try {
return Enum.Parse(_enumType, text);
} catch {
}
throw CreateExceptionForInvalidValue();
}
private ArgumentException CreateExceptionForInvalidValue()
{
string p = string.Join(", ", Enum.GetNames(_enumType));
return new ArgumentException(System.SR.Format(System.SR.Invalid_enum_value, p));
}
}
}