using System; using System.Collections.Generic; using System.Diagnostics; namespace Wayne.Lib { /// /// Enumsupport is a class that has the goal to provide the functionality offered by System.Enum class, but that /// are not available in compact framework. It is very limited in some aspects, so please read carefully the comments of each method. /// public static class EnumSupport { /// /// Gets a list of the enumerated value names for the specified enumeration type. /// NOTE: The enum must not have explicit values set, so there are gaps in the value range, it must start at 0 and go up to max. /// /// /// public static string[] GetNames() { Type type = typeof(TEnumType); if (!type.IsEnum) throw new ArgumentException("Type must be an enumeration."); List names = new List(); int i = 0; while (System.Enum.IsDefined(type, i)) { object oInt = i; TEnumType enumVal = (TEnumType)oInt; object oEnum = enumVal; names.Add((oEnum).ToString()); i++; } return names.ToArray(); } /// /// Gets a list of the enumerated values for the specified enumeration type. /// NOTE: The enum must not have explicit values set, so there are gaps in the value range, it must start at 0 and go up to max. /// /// /// public static TEnumType[] GetValues() { Type type = typeof(TEnumType); if (!type.IsEnum) throw new ArgumentException("Type must be an enumeration."); List values = new List(); int i = 0; while (System.Enum.IsDefined(type, i)) { object o = i; TEnumType et = (TEnumType)o; values.Add(et); i++; } return values.ToArray(); } /// /// Parse a string to an enumeration value given a defaul value if failed. /// /// The enumeration type. /// A string containing the name or value to convert. /// If true, ignore case; otherwise, regard case. /// The default value of the enumeration if the parsing fails. /// [DebuggerStepThrough] public static TEnumType Parse(string value, bool ignoreCase, TEnumType defaultValue) { try { return (TEnumType)Enum.Parse(typeof(TEnumType), value, ignoreCase); } catch (ArgumentException) { return defaultValue; } } /// /// Parse a string to a nullable enumeration value. If it's impossible to parse the string to this /// enumeration type, null is returned. /// /// The enumeration type. /// A string containing the name or value to convert. /// If true, ignore case; otherwise, regard case. /// /// If TEnumType is not an enum. [DebuggerStepThrough] public static TEnumType? ParseDefaultNull(string value, bool ignoreCase) where TEnumType : struct { if (!typeof(TEnumType).IsEnum) throw new ArgumentException("Type T Must be an Enum"); if (string.IsNullOrEmpty(value)) return null; try { return (TEnumType)Enum.Parse(typeof(TEnumType), value.Replace(typeof(TEnumType).Name + ".",""), ignoreCase); } catch (ArgumentException) { return null; } } } }