代码改变世界

C# Enum使用

2023-10-20 14:14  子凡。翅膀  阅读(9)  评论(0编辑  收藏  举报
 1     public enum CoEdit
 2     {
 3         
 4         [Description("通讯开始")]
 5         CommunicationStart = 0001,
 6 
 7         [Description("确认通讯开始")]
 8         NotarizeCommunicationStart = 0002,
 9 
10         [Description("通讯停止")]
11         CommunicationStop = 0003,
12 
13         [Description("命令错误")]
14         CommandError = 0004,
15 
16         [Description("命令已接受")]
17         CommandAccepted = 0005
18     }
19     //主要这个GetDescription()方法,看不懂没关系,如何调用
20     static class EnumExtensions
21     {
22         public static string GetDescription(this Enum val)
23         {
24             var field = val.GetType().GetField(val.ToString());
25             var customAttribute = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute));
26             return customAttribute == null ? val.ToString() : ((DescriptionAttribute)customAttribute).Description;
27         }
28


 //使用时 

Console.WriteLine(EnumExtensions.GetDescription(CoEdit.CommandAccepted)); 

//结果
命令已接受