The C enumeration value is Shared with the transformation instance of the name

  • 2020-05-19 05:33:38
  • OfStack

First, create an enumeration:


/// <summary>
    ///  color 
    /// </summary>
    public enum ColorType
    {
        /// <summary>
        ///  red 
         /// </summary>
        Red,
        /// <summary>
        ///  blue 
         /// </summary>
        Bule,
        /// <summary>
        ///  green 
         /// </summary>
        Green
    }

Obtain enumeration values:


int code = ColorType.Red.GetHashCode();

There are values to get the enumeration name:


string name1=ColorType.Red.ToString();
// or 
string name2= Enum.Parse(typeof(ColorType), code.ToString()).ToString();

The enumeration name obtained above is in English, if you want to get the corresponding Chinese interpretation, you can use Attribute to achieve, the code is as follows:


/// <summary>
    ///  color 
    /// </summary>
    public enum ColorType
    {
        /// <summary>
        ///  red 
        /// </summary>
        [Description(" red ")]
        Red,
        /// <summary>
        ///  blue 
        /// </summary>
        [Description(" blue ")]
        Bule,
        /// <summary>
        ///  green 
        /// </summary>
        [Description(" green ")]
        Green
    }

In the enumeration, add Description, and then create a class, there are the following methods to convert the enumeration to the corresponding Chinese interpretation:


public static class EnumDemo
    {
        private static string GetName(System.Type t, object v)
        {
            try
            {
                return Enum.GetName(t, v);
            }
            catch
            {
                return "UNKNOWN";
            }
        }
        /// <summary>
        ///  Returns a description of the specified value for the specified enumeration type 
         /// </summary>
        /// <param name="t"> Enumerated type </param>
        /// <param name="v"> Enumerated values </param>
        /// <returns></returns>
        public static string GetDescription(System.Type t, object v)
        {
            try
            {
                FieldInfo oFieldInfo = t.GetField(GetName(t, v));
                DescriptionAttribute[] attributes = (DescriptionAttribute[])oFieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
                return (attributes.Length > 0) ? attributes[0].Description : GetName(t, v);
            }
            catch
            {
                return "UNKNOWN";
            }
        }
    }

The method is as follows:


string name3=EnumDemo.GetDescription(typeof(ColorType), ColorType.Red)


Related articles: