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());
            }
  • 相关阅读:
    多级别过滤器
    MongoDBAppender
    org.slf4j.impl.SimpleLoggerFactory cannot be cast to ch.qos.logback.classic.LoggerContext
    简单引入logback
    Logback configuration
    PatternLayoutEncoder 输出格式
    ConsoleAppender
    FileAppender
    Linux学习笔记
    GitLab CI/CD 学习记录
  • 原文地址:https://www.cnblogs.com/athens/p/2671935.html
Copyright © 2011-2022 走看看