zoukankan      html  css  js  c++  java
  • C# 枚举(Enum ) 应用总结

      1. 枚举定义

      普通情况下,枚举字段常数可以是汉字,英文,但不能是数字。当不指定值时,默认值从0开始,如下:待处理=0,审核中=1

     public enum Status
        {        
            待处理,
            审核中,
            交易终止,
            交易完成
        }

      当需要自定义值时则直接在后面赋值即可

     public enum Status
        {        
            待处理 = 0,
            审核中 = 10,
            交易终止 = 20,
            交易完成 = 99
        }

      定义枚举Description

    public enum Status
        {
            [Description("未审核")]
            Untreated = 0,
            [Description("审核中")]
            Process = 10,
            [Description("交易终止")]
            Cancel = 20,
            [Description("交易完成")]
            Over= 99
        }

      2.枚举取值

      通过枚举类型,常量名称取key 

    Status.待处理

      通过枚举类型,和key,获指定的常量名称


    Type type = typeof(Status); String enumName = Enum.GetName(type, key);

      通过枚举类型,和key,获指枚举Description

     public static string GetEnumDescription(Type enumType, int key)
            {
                FieldInfo EnumInfo = enumType.GetField(Enum.GetName(enumType, key));
                DescriptionAttribute[] attributes = (DescriptionAttribute[])EnumInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
                if (attributes.Length > 0)
                {
                    return attributes[0].Description;
                }
                return GetEnumText(enumType, key.ToString());
            }
  • 相关阅读:
    c++<ctime>中常用函数
    头文件<cmath>中常用函数
    c++动态数组的使用
    迭代器与指针
    引用和指针做形参时的区别
    c++使用cin、cout与c中使用scanf、printf进行输入输出的效率问题
    c++指定输出小数的精度
    Linux命令学习(1)
    Nginx 配置文件nginx.conf中文详解
    Walle实现自动发布
  • 原文地址:https://www.cnblogs.com/athens/p/2671935.html
Copyright © 2011-2022 走看看