C# 让枚举返回字符串

时间:2022-09-02 20:16:28

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

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

 

 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