zoukankan      html  css  js  c++  java
  • C# 让枚举返回字符串

    下面的手段是使用给枚举项打标签的方式,来返回字符串

    分别定义一个属性类,一个枚举帮助类

     1 /// <summary>
     2     /// 自定义属性
     3     /// </summary>
     4     [AttributeUsage(AttributeTargets.Field, AllowMultiple = false)]
     5     public sealed class EnumDescriptionAttribute : Attribute
     6     {
     7         private string description;
     8         public string Description { get { return description; } }
     9 
    10         public EnumDescriptionAttribute(string description)
    11             : base()
    12         {
    13             this.description = description;
    14         }
    15     }
    16 
    17     /// <summary>
    18     /// 获取枚举字符串
    19     /// </summary>
    20     public static class EnumHelper
    21     {
    22         public static string GetDescription(Enum value)
    23         {
    24             if (value == null)
    25             {
    26                 throw new ArgumentException("value");
    27             }
    28             string description = value.ToString();
    29             var fieldInfo = value.GetType().GetField(description);
    30             var attributes =
    31                 (EnumDescriptionAttribute[])fieldInfo.GetCustomAttributes(typeof(EnumDescriptionAttribute), false);
    32             if (attributes != null && attributes.Length > 0)
    33             {
    34                 description = attributes[0].Description;
    35             }
    36             return description;
    37         }
    38     }
     1 enum Week  
     2 {  
     3     [EnumDescription("星期一")]  
     4     Monday,  
     5     [EnumDescription("星期二")]  
     6     Tuesday  
     7 }  
     8   
     9 //下面打印结果为: 星期一  
    10 Console.WriteLine(EnuHelper.GetDescription(Week.Monday))  

    转载:http://www.cnblogs.com/xjxz/p/4649016.html 

  • 相关阅读:
    Git常用操作命令
    android快速入门
    使用Jsoup 抓取页面的数据
    js面向对象组件
    js事件详解
    图解TCP-IP协议
    error: linking with `cc` failed: exit code: 1
    git——'fatal: cannot do a partial commit during a merge'
    git add 而未 commit 的文件丢失后找回
    为rust配置国内/科大源
  • 原文地址:https://www.cnblogs.com/louby/p/6549959.html
Copyright © 2011-2022 走看看