在业务开发过程中,添加枚举,在固定枚举值的同时,也需要中文的文案。

如果不想添加语言资源项、添加枚举转语资源项,可以使用特性标记。

属性描述 DescriptionAttribute

先看案例:

     public enum WheelchairDataType
{
[Description("前进加速")]
ForwardAdd,
[Description("前进减速")]
ForwardReduce,
[Description("后退加速")]
BackwardAdd,
[Description("后退减速")]
BackwardReduce,
[Description("转弯加速")]
TurningAdd,
[Description("转弯减速")]
TurningReduce
}
     static void Main(string[] args)
{
var enumDescriptionDict = GetEnumDescriptionDict(WheelchairDataType.BackwardAdd.GetType());
var enumDescription = enumDescriptionDict[WheelchairDataType.BackwardAdd.ToString()];
Console.WriteLine($"{ WheelchairDataType.BackwardAdd.ToString()}:{enumDescription}");
Console.ReadLine();
}

以上,能够直接获取到枚举的描述值。所以我们可以用Description标记,取代我们经常要对枚举添加的中文注释,既是注释也是一种简便的语言项资源。

DescriptionAttribute继承自Attribute,所以枚举的中文标记值,可以通过反射获取:

         /// <summary>
/// 获取枚举/中文字典
/// </summary>
/// <param name="enumType"></param>
/// <returns></returns>
public static Dictionary<string, string> GetEnumDescriptionDict(Type enumType)
{
Dictionary<string, string> dict = new Dictionary<string, string>();
FieldInfo[] fields = enumType.GetFields();
foreach (FieldInfo field in fields)
{
if (field.FieldType.IsEnum)
{
var customAttributes = field.GetCustomAttributes(typeof(DescriptionAttribute), false).ToList();
dict.Add(field.Name, ((DescriptionAttribute)customAttributes[]).Description);
}
} return dict;
}

自定义枚举的描述标记EnumDetailAttribute

如果不想用DescriptionAttribute,或者需要额外的描述信息,可以自定义一个标记。比如:

     public class EnumDetailAttribute : Attribute
{
public string Name { get; set; } public int SpecialOrder { get; set; }
}
     public enum WheelchairDataType
{
[EnumDetail(Name = "前进加速")]
ForwardAdd,
[EnumDetail(Name = "前进减速")]
ForwardReduce,
[EnumDetail(Name = "后退加速")]
BackwardAdd,
[EnumDetail(Name = "后退减速")]
BackwardReduce,
[EnumDetail(Name = "转弯加速")]
TurningAdd,
[EnumDetail(Name = "转弯减速")]
TurningReduce
}
     static void Main(string[] args)
{
Console.WriteLine($"{ WheelchairDataType.BackwardAdd.ToString()}:{ WheelchairDataType.BackwardAdd.GetName()}");
Console.ReadLine();
}

枚举的描述值获取:

     public static class EnumExtensions
{
/// <summary>
/// 获取枚举/中文字典
/// </summary>
/// <param name="enumValue"></param>
/// <returns></returns>
public static Dictionary<string, string> GetEnumDict<TEnum>(this TEnum enumValue) where TEnum : struct
{
Type type = enumValue.GetType(); Dictionary<string, string> dict = new Dictionary<string, string>();
FieldInfo[] fields = type.GetFields();
foreach (FieldInfo field in fields)
{
if (field.FieldType.IsEnum)
{
var customAttributes = field.GetCustomAttributes(typeof(EnumDetailAttribute), false).ToList();
dict.Add(field.Name, ((EnumDetailAttribute)customAttributes[]).Name);
}
} return dict;
}
/// <summary>
/// 获取枚举描述特性值
/// </summary>
/// <typeparam name="TEnum"></typeparam>
/// <param name="enumValue">枚举值</param>
/// <returns>枚举值的描述</returns>
public static string GetName<TEnum>(this TEnum enumValue) where TEnum : struct
{
Type type = enumValue.GetType();
//枚举的成员信息
foreach (var memberInfo in type.GetMembers())
{
if (memberInfo.Name != enumValue.ToString()) continue;
//获取自定义标记
foreach (Attribute attr in memberInfo.GetCustomAttributes(typeof(EnumDetailAttribute), false))
{
var attribute = attr as EnumDetailAttribute;
if (attribute == null) continue;
return attribute.Name;
}
}
return string.Empty;
}
}

C# 添加枚举中文资源的更多相关文章

  1. TensorFlow 中文资源全集,官方网站,安装教程,入门教程,实战项目,学习路径。

    Awesome-TensorFlow-Chinese TensorFlow 中文资源全集,学习路径推荐: 官方网站,初步了解. 安装教程,安装之后跑起来. 入门教程,简单的模型学习和运行. 实战项目, ...

  2. Newtonsoft.Json高级用法之枚举中文转义

    最近看博客园中 焰尾迭的两篇关于"Newtonsoft.Json高级用法"的文章受到了很多人的评论,一度登入到头条推荐. 今天我就不再重复焰尾迭博文中的一些提过的Newtonsof ...

  3. 【转】利用Eclipse编辑中文资源文件(application_zh_CN.properties )

    既然生为中国人,就没有什么好抱怨的了,遇到编码的问题,那只有解决它了. 如果经常使用Struts,并做过国际化操作的人来说,对于中文资源文件的处理应该不会感到陌生的.比如下面两个文件,一个是英文的,一 ...

  4. TensorFlow 中文资源精选,官方网站,安装教程,入门教程,实战项目,学习路径。

    Awesome-TensorFlow-Chinese TensorFlow 中文资源全集,学习路径推荐: 官方网站,初步了解. 安装教程,安装之后跑起来. 入门教程,简单的模型学习和运行. 实战项目, ...

  5. Redis最有用的中文资源,你值得拥有

    只是为了记录资源地址,最好直接访问doc.redisfans.com更美观 Redis 命令参考 本文档是 Redis Command Reference 和 Redis Documentation ...

  6. python中文资源大全

    Python 资源大全中文版 我想很多程序员应该记得 GitHub 上有一个 Awesome - XXX 系列的资源整理.awesome-python 是 vinta 发起维护的 Python 资源列 ...

  7. ASP.NET Core中结合枚举和资源文件显示列表

    模型类的某些属性以枚举形式出现,我们希望在打开编辑表单时在选择列表中显示枚举值.有时我们想要枚举元素名称,但有时我们想要使用自定义名称甚至翻译. 这个例子演示了如何获取枚举元素名称以选择ASP.NET ...

  8. 对本地Solr服务器添加IK中文分词器实现全文检索功能

    在上一篇随笔中我们提到schema.xml中<field/>元素标签的配置,该标签中有四个属性,分别是name.type.indexed与stored,这篇随笔将讲述通过设置type属性的 ...

  9. springboot 1.5.2 thymeleaf 添加templates 静态资源访问路径

    从velocity 模板切换到thymeleaf 后, 默认模板位置为templates , 有时候静态资源方在该目录下会出现访问404错误 解决办法: application.properties ...

随机推荐

  1. mybatis 异常Result Maps collection does not contain value for java.lang.String

    Result Maps collection does not contain value for java.lang.String 以上是我报的错. 只要报Result Maps collectio ...

  2. JVM学习记录-类加载的过程

    类的整个生命周期的7个阶段是:加载(Loading).验证(Verification).准备(Preparation).解析(Resolution).初始化(Initialization).使用(Us ...

  3. sum() 函数性能堪忧,列表降维有何良方?

    本文原创并首发于公众号[Python猫],未经授权,请勿转载. 原文地址:https://mp.weixin.qq.com/s/mK1nav2vKykZaKw_TY-rtw Python 的内置函数 ...

  4. com.netflix.discovery.shared.transport.TransportException: Cannot execute request on any known server 报错问题

    com.netflix.discovery.shared.transport.TransportException: Cannot execute request on any known serve ...

  5. SSL,TLS

    今天突然收到邮件说SSL不能用了,基于SSL的HTTPS协议不通了,怎么办? java/android 的网络编程简直一窍不通,平时都是用到了问百度.只能恶补有关网络的知识了. 传输协议: 传输协议中 ...

  6. Python爬虫入门教程 57-100 python爬虫高级技术之验证码篇3-滑动验证码识别技术

    滑动验证码介绍 本篇博客涉及到的验证码为滑动验证码,不同于极验证,本验证码难度略低,需要的将滑块拖动到矩形区域右侧即可完成. 这类验证码不常见了,官方介绍地址为:https://promotion.a ...

  7. .Net Core使用Redis(CSRedis)

    前言 CSRedis是国外大牛写的.git地址:https://github.com/2881099/csredis,让我们看看如果最简单的 使用一下CSRedis吧. 引入NuGet 获取Nuget ...

  8. 使用Springboot + Gradle快速整合Mybatis-Plus

    使用Springboot + Gradle快速整合Mybatis-Plus 作者:Stanley 罗昊 [转载请注明出处和署名,谢谢!] MyBatis-Plus(简称 MP)是一个 MyBatis ...

  9. Java 在PDF文档中绘制图形

    本篇文档将介绍通过Java编程在PDF文档中绘制图形的方法.包括绘制矩形.椭圆形.不规则多边形.线条.弧线.曲线.扇形等等.针对方法中提供的思路,也可以自行变换图形设计思路,如菱形.梯形或者组合图形等 ...

  10. iOS----------Runtime 获取属性列表 方法列表

    导入 #import <objc/runtime.h> unsigned int count; Method *methods = class_copyMethodList([UIAler ...