当前位置: 首页 > news >正文

C#高级:枚举(Enum)从索引、值到注释的完整使用技巧

目录

一、推荐的枚举写法

二、获取注释的封装代码

三、已知【枚举】,获取注释、索引

四、已知【索引】,获取枚举值、注释

五、已知【注释】,获取枚举值、索引

六、创建一个【枚举字典】,key=索引,value=(枚举值,注释)

七、全部代码展示(控制台程序)

八、输出结果


一、推荐的枚举写法

 public enum Level{[Description("无")]None = 0,[Description("一般")]Normal = 1,[Description("重要")]Important = 2,[Description("紧急")]Urgent = 3}

【不推荐的写法】没有索引值(或者索引值用字符串)、不写注释、命名马虎等

二、获取注释的封装代码

private static string GetEnumDescription(Enum value)
{var fieldInfo = value.GetType().GetField(value.ToString());var attribute = (DescriptionAttribute)Attribute.GetCustomAttribute(fieldInfo, typeof(DescriptionAttribute));return attribute?.Description ?? value.ToString();
}

【说明】有了上述该代码,实现索引、注释、枚举字符串的转化就相当容易了!

三、已知【枚举】,获取注释、索引

 Level enumdata = Level.Important;Console.WriteLine($"注释:{GetEnumDescription(enumdata)}");Console.WriteLine($"索引:{enumdata.GetHashCode()}");

四、已知【索引】,获取枚举值、注释

  int index = 1;Console.WriteLine($"枚举值(Level):{(Level)index}");Console.WriteLine($"枚举值(string):{((Level)index).ToString()}");Console.WriteLine($"注释(string):{GetEnumDescription((Level)index)}");

五、已知【注释】,获取枚举值、索引

这里需要多封装一个方法,如下所示:

 public static TEnum GetEnumByDescription<TEnum>(string description)where TEnum : Enum{foreach (var field in typeof(TEnum).GetFields(BindingFlags.Public | BindingFlags.Static)){if (Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) is DescriptionAttribute attribute){if (attribute.Description == description){return (TEnum)field.GetValue(null);}}}throw new ArgumentException($"枚举类型 {typeof(TEnum).FullName} 中找不到描述为 '{description}' 的枚举成员。");}

实现代码:

Level enumresult = GetEnumByDescription<Level>("紧急");
Console.WriteLine($"枚举值:{enumresult}");
Console.WriteLine($"索引值:{enumresult.GetHashCode()}");

六、创建一个【枚举字典】,key=索引,value=(枚举值,注释)

这里需要多封装一个方法,如下所示:

 private static Dictionary<int, (T, string)> GetDictionaryByEnum<T>() where T : Enum{// 创建一个字典来存储索引和枚举值/注释的对应关系Dictionary<int, (T, string)> enumDictionary = new Dictionary<int, (T, string)>();// 遍历枚举成员foreach (T enumValue in Enum.GetValues(typeof(T))){// 获取枚举成员的整数值int enumIndex = enumValue.GetHashCode();// 获取枚举成员的描述信息(注释)string enumDescription = GetEnumDescription(enumValue);// 将索引和枚举值/注释的对应关系存入字典enumDictionary.Add(enumIndex, ((T)enumValue, enumDescription));}return enumDictionary;}

实现代码:

var dict = GetDictionaryByEnum<Level>();
foreach (var item in dict)
{Console.WriteLine($"索引:{item.Key},枚举值:{item.Value.Item1},注释:{item.Value.Item2}");
}

七、全部代码展示(控制台程序)

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Xml.Linq;namespace ConsoleApp1
{public class Program{public static TEnum GetEnumByDescription<TEnum>(string description)where TEnum : Enum{foreach (var field in typeof(TEnum).GetFields(BindingFlags.Public | BindingFlags.Static)){if (Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) is DescriptionAttribute attribute){if (attribute.Description == description){return (TEnum)field.GetValue(null);}}}throw new ArgumentException($"枚举类型 {typeof(TEnum).FullName} 中找不到描述为 '{description}' 的枚举成员。");}private static string GetEnumDescription(Enum value){var fieldInfo = value.GetType().GetField(value.ToString());var attribute = (DescriptionAttribute)Attribute.GetCustomAttribute(fieldInfo, typeof(DescriptionAttribute));return attribute?.Description ?? value.ToString();}private static Dictionary<int, (T, string)> GetDictionaryByEnum<T>() where T : Enum{// 创建一个字典来存储索引和枚举值/注释的对应关系Dictionary<int, (T, string)> enumDictionary = new Dictionary<int, (T, string)>();// 遍历枚举成员foreach (T enumValue in Enum.GetValues(typeof(T))){// 获取枚举成员的整数值int enumIndex = enumValue.GetHashCode();// 获取枚举成员的描述信息(注释)string enumDescription = GetEnumDescription(enumValue);// 将索引和枚举值/注释的对应关系存入字典enumDictionary.Add(enumIndex, ((T)enumValue, enumDescription));}return enumDictionary;}public enum Level{[Description("无")]None = 0,[Description("一般")]Normal = 1,[Description("重要")]Important = 2,[Description("紧急")]Urgent = 3}static void Main(string[] args){//1.已知【枚举】,获取注释、索引Level enumdata = Level.Important;Console.WriteLine($"注释:{GetEnumDescription(enumdata)}");Console.WriteLine($"索引:{enumdata.GetHashCode()}");////2.已知【索引】,获取枚举值、注释int index = 1;Console.WriteLine($"枚举值(Level):{(Level)index}");Console.WriteLine($"枚举值(string):{((Level)index).ToString()}");Console.WriteLine($"注释(string):{GetEnumDescription((Level)index)}");//3.已知【注释】,获取枚举值、索引Level enumresult = GetEnumByDescription<Level>("紧急");Console.WriteLine($"枚举值:{enumresult}");Console.WriteLine($"索引值:{enumresult.GetHashCode()}");//4.创建一个【枚举字典】,key=索引,value=(枚举值,注释)var dict = GetDictionaryByEnum<Level>();foreach (var item in dict){Console.WriteLine($"索引:{item.Key},枚举值:{item.Value.Item1},注释:{item.Value.Item2}");}}}}

八、输出结果

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • 养猫老手激情开麦!希喂白小罐试吃测评分享!
  • Leetcode 11. 盛最多水的容器
  • 【Django5】模型定义与使用
  • 小程序、H5、APP中的微信支付概述和实战总结
  • 【机器学习】Jupyter Notebook如何使用之基本步骤和进阶操作
  • Kafka、RabbitMQ、RocketMQ:消息队列技术深度对比
  • C++:map和set
  • 实验4-2-2 使用函数求e的近似值
  • vue里给img的src绑定数据失效
  • Redis 缓存
  • 《Java8函数式编程》学习笔记汇总
  • 科普文:从源码解读5种Redis基本数据类型
  • leetcode 2236.判断根节点是否等于字节点
  • MOELayer DEMO及注释
  • 你想活出怎样的人生?我只活一次,所以想做自己
  • [PHP内核探索]PHP中的哈希表
  • ES6系统学习----从Apollo Client看解构赋值
  • ES学习笔记(12)--Symbol
  • Javascript编码规范
  • Node 版本管理
  • Quartz实现数据同步 | 从0开始构建SpringCloud微服务(3)
  • Redis中的lru算法实现
  • Theano - 导数
  • 警报:线上事故之CountDownLatch的威力
  • 蓝海存储开关机注意事项总结
  • 漫谈开发设计中的一些“原则”及“设计哲学”
  • 浅谈JavaScript的面向对象和它的封装、继承、多态
  • 容器化应用: 在阿里云搭建多节点 Openshift 集群
  • 如何打造100亿SDK累计覆盖量的大数据系统
  • 删除表内多余的重复数据
  • 少走弯路,给Java 1~5 年程序员的建议
  • 使用 5W1H 写出高可读的 Git Commit Message
  • 小程序上传图片到七牛云(支持多张上传,预览,删除)
  • ###51单片机学习(1)-----单片机烧录软件的使用,以及如何建立一个工程项目
  • $LayoutParams cannot be cast to android.widget.RelativeLayout$LayoutParams
  • (145)光线追踪距离场柔和阴影
  • (30)数组元素和与数字和的绝对差
  • (java版)排序算法----【冒泡,选择,插入,希尔,快速排序,归并排序,基数排序】超详细~~
  • (第27天)Oracle 数据泵转换分区表
  • (附源码)spring boot基于小程序酒店疫情系统 毕业设计 091931
  • (附源码)ssm基于web技术的医务志愿者管理系统 毕业设计 100910
  • (九)One-Wire总线-DS18B20
  • (四)React组件、useState、组件样式
  • (转)JVM内存分配 -Xms128m -Xmx512m -XX:PermSize=128m -XX:MaxPermSize=512m
  • .net CHARTING图表控件下载地址
  • .NET Core 将实体类转换为 SQL(ORM 映射)
  • .net core 依赖注入的基本用发
  • .net 后台导出excel ,word
  • @JsonFormat与@DateTimeFormat注解的使用
  • @PostConstruct 注解的方法用于资源的初始化
  • [].shift.call( arguments ) 和 [].slice.call( arguments )
  • [BUUCTF NewStarCTF 2023 公开赛道] week4 crypto/pwn
  • [C#][opencvsharp]opencvsharp sift和surf特征点匹配
  • [C#小技巧]如何捕捉上升沿和下降沿
  • [codeforces]Recover the String