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
  • 相关阅读:
    Https协议详解
    python3爬虫之入门和正则表达式
    浅谈httpsssl数字证书
    Linux常见配置文件
    标准C++中的string类的用法总结
    SourceInsight中 加namespace宏后,无法跳转问题解决
    ubuntu 12.04安装vmtools 问题解决
    Prolific PL2303 usb 转串口Win8 Win8.1驱动
    大津法阈值法代码
    opencv常用函数备忘
  • 原文地址:https://www.cnblogs.com/chenpanpan/p/14506271.html
Copyright © 2011-2022 走看看