C#枚举基础解析

       枚举提供成组的常数值,它们有助于使成员成为强类型以及提高代码的可读性。在 C# 中,使用 enum 来声明枚举。 所有的枚举类型都是从System.Enum抽象类派生的,后者又是从System.ValueType派生,因此所有的枚举类型都是值类型。

      enum 关键字用于声明枚举,即一种由一组称为枚举数列表的命名常数组成的独特类型。每种枚举类型都有基础类型,该类型可以是除 char 以外的任何整型。枚举元素的默认基础类型为 int。默认情况下,第一个枚举数的值为 0,后面每个枚举数的值依次递增 1。

基本语法:

   enum Day { Sun, Mon, Tue, Wed, Thu, Fri, Sat };

枚举中的值中不能包含有空格

     基础类型指定为每个枚举数分配的存储大小。但是,从 enum 类型到整型的转换需要用显式类型转换来完成。例如,下面的语句通过使用强制转换从 enum 转换为 int,将枚举数 Sun 赋给 int 类型的变量:

        int x = (int)Days.Sun;

        Day m=(Day)1;

 Enum类

枚举提供基类。

     

Parse(Type, String) 将一个或多个枚举常数的名称或数字值的字符串表示转换成等效的枚举对象。

        enum Colors { None=0, Red = 1, Green = 2, Blue = 4 };

        Colors colorValue = (Colors) Enum.Parse(typeof(Colors), Red);

IsDefined 返回指定枚举中是否存在具有指定值的常数的指示。返回值是个布尔类型

         Enum.IsDefined(typeof(Colors), colorValue)

Enumeration变量的文字描述

      如果想要Enumeration返回一点有意义的string,从而用户能知道分别代表什么, 则按如下定义:
using System.ComponentModel; // 先添加该引用

 public enum Nation : byte
    {
        [Description("Chưa biết")]
        未知=0,
        [Description("Liên Minh")]
        联盟 = 1,
        [Description("Bộ Lạc")]
        部落 = 2,
    }

使用如下方法来获得文字描述:
using System.Reflection;
using System.ComponentModel;

publicstaticString GetEnumDesc(Enum enumSubitem)
{

            string strValue = enumSubitem.ToString();

            FieldInfo fieldinfo = enumSubitem.GetType().GetField(strValue);
            Object[] objs = fieldinfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
            if (objs == null || objs.Length == 0)
            {
                return strValue;
            }
            else
            {
                DescriptionAttribute da = (DescriptionAttribute)objs[0];
                return da.Description;
            }


}

  

原文地址:https://www.cnblogs.com/h20064528/p/2469306.html