zoukankan      html  css  js  c++  java
  • c# 获取枚举类型的描述description及枚举类型的值

    枚举类:

     1 using System;
     2 using System.Collections.Generic;
     3 using System.ComponentModel;
     4 using System.Linq;
     5 using System.Text;
     6 
     7 namespace DevOps.Commn
     8 {
     9    public static class Enums
    10     {
    11         /// <summary>
    12         /// 文档状态
    13         /// </summary>
    14         public enum DocStatus
    15         {
    16             /// <summary>
    17             /// 草稿
    18             /// </summary>
    19             [Description("草稿")]
    20             Draft = 1,
    21             /// <summary>
    22             /// 已发布
    23             /// </summary>
    24             [Description("已发布")]
    25             Published = 2,
    26             /// <summary>
    27             /// 撤回
    28             /// </summary>
    29            [Description("撤回")]
    30             Withdraw = 3
    31         }
    32 
    33         public static string GetEnumDesc<T>(T tField)
    34         {
    35             var description = string.Empty; //结果
    36             var inputType = tField.GetType(); //输入的类型
    37             var descType = typeof(DescriptionAttribute); //目标查找的描述类型
    38 
    39             var fieldStr = tField.ToString();                //输入的字段字符串
    40             var field = inputType.GetField(fieldStr);        //目标字段
    41 
    42             var isDefined = field.IsDefined(descType, false);//判断描述是否在字段的特性
    43             if (isDefined)
    44             {
    45                 var EnumAttributes = (DescriptionAttribute[])field        //得到特性信息
    46                     .GetCustomAttributes(descType, false);
    47                 description = EnumAttributes.FirstOrDefault()?.Description ?? string.Empty;
    48             }
    49             return description;
    50         }
    51     }
    52 }

    调用方法:

    1  var EnumDesc = GetEnumDesc(DocStatus.Published);//"已发布"
    2  var EnumValue = (int)DocStatus.Draft;//1
  • 相关阅读:
    精细化python 类的内置属性
    python操作excel
    ghost linux
    Linux dd 命令
    Ubantu 使用root登陆的方法
    NSIS Error: "Error writing temporary file. Make sure your temp folder is valid
    error writing temporary file。make sure your temp folder is valid 问题已解决
    安卓电池状态监听
    Android源码下载
    vim插件详细安装过程
  • 原文地址:https://www.cnblogs.com/chenpanpan/p/14506271.html
Copyright © 2011-2022 走看看