枚举学习文摘 — 框架设计(第2版) CLR Via C#

发现对枚举的一些用法还不太熟悉,重新翻看了框架设计(第2版) CLR Via C#一书,整理了一下。

声明枚举类型:

internal enum Color
        {
            White,
            Red,
            Green,
            Blue,
            Orange
        }

1、Enum类型的静态方法GetUnderlyingType:

   Public static Type GetUnderlyingType(Type enumType);

   该方法返回用于容纳枚举类型值的核心类型。每个枚举类型都有一个基本类型,该类型可以是一个byte,sbyte,short,ushort,int(最常见,也是默认的),uint,long或ulong。

   声明一个基本类型为byte(System.Byte)的枚举类型:

  internal enum Color : byte
        {
            White,
            Red,
            Green,
            Blue,
            Orange
        }

  Console.WriteLine(Enum.GetUnderlyingType(typeof(Color)));  //输出System.Byte

2、基于一个枚举类型的实例,可以调用从System.Enum继承的ToString方法,把它的值映射为以下几个字符串表示中的一个:
 
  Color c = Color.Blue;
  Console.WriteLine(c);               //"Blue" (泛型格式)
  Console.WriteLine(c.ToString());    //"Blue"(泛型格式)
  Console.WriteLine(c.ToString("G")); //"Blue"(泛型格式)
  Console.WriteLine(c.ToString("D")); //"3"(十进制格式)
  Console.WriteLine(c.ToString("X"));//"03"(十六进制格式,输出数位个数取决于enum的基本类型)
           
3、Enum类型还提供一个静态方法Format,格式化一个枚举类型的值:

  public static String Format(Type enumType, Object value, String format);

  使用Format方法有一个优势,允许为value参数传递一个数值,这样就不必非要有枚举类型的一个实例。
 
  Console.WriteLine(Enum.Format(typeof(Color),3,"G"));//输出"Blue"

4、Enum类型的静态方法GetValues,获取一个数组,该数组的每个元素都对应于枚举类型中的一个符号名称,每个元素都包含符号名称的值:

   public static Array GetValues(Type enumType);

   这个方法结合ToString方法使用,可以显示枚举类型中的所有符号名称及其对应的数值:

 
  Color[] colors = (Color[])Enum.GetValues(typeof(Color));
  Console.WriteLine("Number of symbol defined:" + colors.Length);
  Console.WriteLine("Value\tSymbol\n-----\t-----");
  foreach (Color c in colors)
      Console.WriteLine(c.ToString("D") + "   " + c.ToString("G"));


输出如下:

Number of symbol defined:5
Value   Symbol
-----   -----
0   White
1   Red
2   Green
3   Blue
4   Orange


4、Enum类型的另一个静态方法Parse,将一个符号转换为枚举类型的一个实例:
 
  public static Object Parse(Type enumType, String value);
  public static Object Parse(Type enumType, String value, Boolean ignoreCase);

  Color c = (Color)Enum.Parse(typeof(Color), "orange", true);
  Console.WriteLine(c.ToString("D")); //"4"

  Color c2 = (Color)Enum.Parse(typeof(Color), "1", false);
  Console.WriteLine(c2.ToString()); //"Red"

------------------------------------------------------------------------------------------------

另:枚举显示中文

http://www.cnblogs.com/steden/archive/2009/12/22/1629515.html

TeType.cs

using System;
using System.ComponentModel;

public enum TeType
{
    [Description("测试文本1")]
    Ta = 0,

    [Description("测试文本2")]
    Tb = 1
}

ParseEnum.cs

 /// <summary>
    /// 枚举
    /// </summary>
    public class ParseEnum
    {
        public static Dictionary<string, string> dicEnum = new Dictionary<string, string>();

         ///   <summary>  
        ///   根据Value获取枚举值的详细文本  
        ///   </summary>   
        public static string GetDescByVal(Type enumType, string enumVal)
        {          
            string text = Enum.Parse(enumType, enumVal, true).ToString();
            return GetDescByText(enumType, text);
        }

        ///   <summary>  
        ///   根据Text获取枚举值的详细文本  
        ///   </summary>   
        public static string GetDescription(Type enumType, string enumName)
        {
            string key = string.Format("{0}.{1}", enumType.Name, enumName);

            if (dicEnum.ContainsKey(key)) { return dicEnum[key]; }

            //获取字段信息  
            System.Reflection.FieldInfo[] ms = enumType.GetFields();

            foreach (System.Reflection.FieldInfo f in ms)
            {
                //判断名称是否相等  
                if (f.Name != enumName) continue;

                //反射出自定义属性  
                foreach (Attribute attr in f.GetCustomAttributes(true))
                {
                    //类型转换找到一个Description,用Description作为成员名称  
                    System.ComponentModel.DescriptionAttribute dscript = attr as System.ComponentModel.DescriptionAttribute;
                    if (dscript != null)
                    {
                        dicEnum.Add(key, dscript.Description);
                        return dscript.Description;
                    }
                }

            }

            //如果没有检测到合适的注释,则用默认名称  
            return enumName;
        }

        /// <summary>
        /// 获取枚举的字典列表
        /// </summary>
        /// <param name="enumType"></param>
        /// <returns></returns>
        public static Dictionary<int, string> GetEnumList(Type enumType)
        {
            Dictionary<int, string> dict = new Dictionary<int, string>();
            foreach (int value in Enum.GetValues(enumType))
            {
                string name = Enum.GetName(enumType, value);
                if(!dict.ContainsKey(value))
                    dict.Add(value, ParseEnum.GetDescription(enumType, name));
            }
            return dict;
        }
       
    }


TestPage.aspx.cs

  /// <summary>
        /// 绑定类型下拉框
        /// </summary>
        protected void BindDdlType()
        {
            Dictionary<int, string> dict = ParseEnum.GetEnumList(typeof(TeType));
            ddlType.DataSource = dict;
            ddlType.DataValueField = "key";
            ddlType.DataTextField = "value";
            ddlType.DataBind();
            ddlType.Items.Insert(0, new ListItem("-- 所有类型 --", ""));        
        }

原文地址:https://www.cnblogs.com/gdjlc/p/2086910.html