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

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

 

[csharp] view plaincopyprint?转-C#让枚举返回字符串转-C#让枚举返回字符串
 
  1. [AttributeUsage(AttributeTargets.Field,AllowMultiple = false)]  
  2. public sealed class EnumDescriptionAttribute : Attribute  
  3. {  
  4.     private string description;  
  5.     public string Description { get { return description; } }  
  6.   
  7.     public EnumDescriptionAttribute(string description)  
  8.         : base()  
  9.     {  
  10.         this.description = description;  
  11.     }  
  12. }  
[csharp] view plaincopyprint?转-C#让枚举返回字符串转-C#让枚举返回字符串
 
  1. public static class EnumHelper  
  2. {  
  3.     public static string GetDescription(Enum value)  
  4.     {  
  5.         if (value == null)  
  6.         {  
  7.             throw new ArgumentException("value");  
  8.         }  
  9.         string description = value.ToString();  
  10.         var fieldInfo = value.GetType().GetField(description);  
  11.         var attributes =  
  12.             (EnumDescriptionAttribute[]) fieldInfo.GetCustomAttributes(typeof (EnumDescriptionAttribute), false);  
  13.         if (attributes != null && attributes.Length > 0)  
  14.         {  
  15.             description = attributes[0].Description;  
  16.         }  
  17.         return description;  
  18.     }  
  19. }  

使用举例:

 

 

[csharp] view plaincopyprint?转-C#让枚举返回字符串转-C#让枚举返回字符串
 
  1. enum Week  
  2. {  
  3.     [EnumDescription("星期一")]  
  4.     Monday,  
  5.     [EnumDescription("星期二")]  
  6.     Tuesday  
  7. }  
  8.   
  9. //下面打印结果为: 星期一  
  10. Console.WriteLine(EnuHelper.GetDescription(Week.Monday))  

相关文章:

  • 2021-06-22
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-02-16
  • 2021-11-16
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-05-18
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案