有时候我们用数字来区分一些类型,如1:中国银行,2:建设银行,3:工商银行,……。
这时候我在代码中通常会定义枚举来与定义的一一对应,并在该枚举值上设置特性来表示所代表的含义,这样避免多处写一些数字来标识所代表的类型。而且后续添加修改也很方便。


首先,自定义一个特性描述类:
 1     public class DescriptionAttribute : Attribute
 2     {
 3         public static readonly DescriptionAttribute Default;
 4 
 5         public DescriptionAttribute();
 6         public DescriptionAttribute(string description);
 7 
 8         public virtual string Description { get; }
 9         protected string DescriptionValue { get; set; }
10 
11         public override bool Equals(object obj);
12         public override int GetHashCode();
13     }

定义枚举:
1 public enum EnumType
2 3   [Description("第一")]
4   FIRST,
5   [Description("第二")]
6   SECOND,
7   [Description("第三")]
8   THIRD,
9

将枚举特性值转为注释信息:
 1         /// <summary>
 2         /// 将枚举特性值转为注释信息
 3         /// </summary>
 4         /// <param name="enumType"></param>
 5         /// <returns></returns>
 6         public static string ToString<T>(this T enumType)
 7         {
 8             Type type = enumType.GetType();
 9             FieldInfo fd = type.GetField(enumType.ToString());
10             if (fd == null)
11                 return string.Empty;
12             var attributes = fd.GetCustomAttributes(typeof(DescriptionAttribute), false);
13 
14             var txt = string.Empty;
15             foreach (DescriptionAttribute attr in attributes)
16             {
17                 txt = attr.Description;
18                 break;
19             }
20             return txt;
21         }

 

调用:

1 var name = EnumType.FIRST.ToString<EnumType>();
2 //第一

 


相关文章:

  • 2021-09-20
  • 2022-12-23
  • 2021-11-24
  • 2021-11-04
  • 2022-12-23
  • 2022-12-23
  • 2021-12-29
猜你喜欢
  • 2021-09-04
  • 2021-06-18
  • 2022-01-14
  • 2021-08-06
  • 2022-12-23
  • 2022-02-09
相关资源
相似解决方案