////////////////////////////////////////////////// /// /// <author>Nicholas Paldino</author> /// <created>2013-10-22</created> /// <summary>Gets the <see cref="EnumCodeAttribute.Code"/> /// property given a value from an enumeration.</summary> /// <typeparam name="T">The type of the enumeration /// to get the <see cref="EnumCodeAttribute"/> /// from.</typeparam> /// <param name="value">The value from the enumeration type /// <typeparamref name="T"/> to get the attribute for.</param> /// <returns>The <see cref="EnumCodeAttribute.Code"/> or null /// if there is none.</returns> /// ////////////////////////////////////////////////// public static string GetEnumCodeAttributeCode <T>(T value) where T : struct { // Get the attribute. EnumCodeAttribute attribute = GetEnumCodeAttribute(value); // If it is null, return null, otherwise, // return the code. return(attribute?.Code); }
////////////////////////////////////////////////// /// /// <author>Nicholas Paldino</author> /// <created>2012-07-28</created> /// <summary>Sets up the <see cref="IDictionary{TKey,TValue}"/> /// that maps the code to the <typeparamref name="T"/>.</summary> /// <typeparam name="T">The enumeration type.</typeparam> /// <returns>The <see cref="IDictionary{TKey,TValue}"/> /// that is the map between the code and the /// enumeration value.</returns> /// ////////////////////////////////////////////////// private static IDictionary <string, T> SetupTryGetByEnumCodeMap <T>(bool ignoreCase) where T : struct { // Get the type. Type t = typeof(T); // The type is an enumeration. Debug.Assert(t.GetTypeInfo().IsEnum); // Create the lookup. IDictionary <string, T> lookup = new Dictionary <string, T>(ignoreCase ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal); // Cycle through all of the fields. foreach (KeyValuePair <T, FieldInfo> pair in GetEnumFieldsDictionary <T>()) { // Get the field info. FieldInfo fi = pair.Value; // The declaring type is not null. Debug.Assert(fi.DeclaringType != null); // If the attribute does not exist on the type, then throw // an exception. EnumCodeAttribute attribute = pair.Value.GetCustomAttributes <EnumCodeAttribute>(true).SingleOrDefault(); // If the attribute is null, throw an exception. if (attribute == null) { throw new InvalidOperationException( string.Format(CultureInfo.InvariantCulture, "The {0} value in the {1} enumeration does not have the EnumCodeAttribute applied to it.", fi.Name, fi.DeclaringType.FullName)); } // The looked up value. T value; // Try and look up, it should not succeed. if (lookup.TryGetValue(attribute.Code, out value)) { // Throw an exception. throw new InvalidOperationException( string.Format(CultureInfo.InvariantCulture, "The code \"{0}\" is already applied to another value in the {1} enumeration.", attribute.Code, fi.DeclaringType.FullName)); } // Add the value. lookup.Add(attribute.Code, pair.Key); } // Return the lookup. return(lookup); }