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

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

属性描述 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. MYSQL—— 完整性约束条件中primary key、auto_increment使用总结!

    完整性约束条件主要有:primary key(主键), auto_increment(自增长), poreign key(外键), not null(非空), unique key(唯一), defa ...

  2. 伪元素before after

    什么是伪元素(Pseudo element)? 伪元素不是真正的元素,不存在与文档之中,所以js无法操作他.那为什么叫他"元素"?因为我们可以对其进行跟元素几乎无差别的操作. 伪元 ...

  3. UWP中实现大爆炸效果(二)

    上一回实现了一个宽度不均匀的Panel,这次我们编写一个简单的BigbangView主体. 首先创建一个模板化控件,删掉Themes/Generic.xaml中的<Style TargetTyp ...

  4. Xshell访问和连接Linux

    Xshell是一款强大的安全终端模拟软件,Xshell 模拟了远程主机的操作,其实质就是通过访问和连接到远程主机,在本地实现对远程主机的操作.  一.下载 官网:https://www.netsara ...

  5. 一文读懂Asp.net core 依赖注入(Dependency injection)

    一.什么是依赖注入 首先在Asp.net core中是支持依赖注入软件设计模式,或者说依赖注入是asp.net core的核心: 依赖注入(DI)和控制反转(IOC)基本是一个意思,因为说起来谁都离不 ...

  6. Vue.js组件间通信方式总结

    平时在使用Vue框架的业务开发中,组件不仅仅要把模板的内容进行复用,更重要的是组件之间要进行通信.组件之间通信分为三种:父-子:子-父:跨级组件通信.下面,就组件间如何通信做一些总结. 1.父组件到子 ...

  7. PostgreSql 使用dblink跨库

    此篇介绍下psql下dblink的使用方式,帮助自己记录以备后需.dblink是psql下的扩展功能,可以实现在一个数据库中远程操作另外一个数据库,是实现跨库的一种方法.下面步入正文. 安装dblin ...

  8. Windows -- cmd命令: ipconfig 和 nbtstat

    1. ipconfig 命令格式及参数如下: 2. nbtstat 命令格式及参数如下:

  9. Error:"MetaStoreClient lost connection. Attempting to reconnect (1 of 24) after 5s. getCurrentNotificationEventId" occurs as HiveServer2 fails to start as it cannot connect to Metastore in HDP 3.0

    SupportKB Problem Description:After upgrading to HDP 3.0, the HiveServer2 fails to start and the fol ...

  10. ASP.NET开发中修改代码而不重启网站

    我们在做网站开发的时候,通常是写好了一个功能就要进行测试,Visual Studio上点“Start Debugging”(快捷键是F5),这是调试模式,也有直接运行模式,“Start Without ...