博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
枚举类型转换成字符串
阅读量:4677 次
发布时间:2019-06-09

本文共 2162 字,大约阅读时间需要 7 分钟。

使用枚举类型默认的ToString()方法,往往不能得到我们想要的输出的字符串。

如何方便的定义枚举类型中的每个值代表的字符串输出呢?
可以使用DescriptionAttribute, 写上想得到的字符串输出。

enum Direction{    [Description("Rover is facing to UP (Negtive Y)")]    UP = 1,    [Description("Rover is facing to DOWN (Positive Y)")]    DOWN = 2,    [Description("Rover is facing to RIGHT (Positive X)")]    RIGHT = 3,    [Description("Rover is facing to LEFT (Negtive X)")]    LEFT = 4};

使用下面的方法,来得到对应项的字符串。

///     /// Contains methods for working with 
. ///
public static class EnumHelper { /// /// Gets the specified enum value's description. /// /// The enum value. ///
The description or
null
/// if enum value doesn't have
.
public static string GetDescription(this Enum value) { var fieldInfo = value.GetType().GetField(value.ToString()); var attributes = (DescriptionAttribute[])fieldInfo.GetCustomAttributes( typeof(DescriptionAttribute), false); return attributes.Length > 0 ? attributes[0].Description : null; } /// /// Gets the enum value by description. /// ///
The enum type.
/// The description. ///
The enum value.
public static EnumType GetValueByDescription
(string description) { var type = typeof(EnumType); if (!type.IsEnum) throw new ArgumentException("This method is destinated for enum types only."); foreach (var enumName in Enum.GetNames(type)) { var enumValue = Enum.Parse(type, enumName); if (description == ((Enum)enumValue).GetDescription()) return (EnumType)enumValue; } throw new ArgumentException("There is no value with this description among specified enum type values."); } }

 进一步了解

转载于:https://www.cnblogs.com/JustRun1983/archive/2012/06/22/2559073.html

你可能感兴趣的文章
计算机基本介绍
查看>>
使用Flickr的图片拼出你的句子
查看>>
Visual Studio中web应用程序和网站区别
查看>>
浅析/dev/shm
查看>>
BZOJ4010 HNOI2015 菜肴制作 拓扑排序+贪心
查看>>
处理打拼音时触发input事件bug
查看>>
074-PHP数组元素相乘
查看>>
Android性能调优篇之UI布局优化
查看>>
DateUtils
查看>>
Java -- IO -- 目录
查看>>
三路快速排序
查看>>
不能出现W3!!
查看>>
【Linux笔记(002) 】-- centos7 文档操作基本命令
查看>>
【算法总结】动态规划-背包问题
查看>>
EF性能优化
查看>>
网络流24题——试题库问题
查看>>
数据挖掘:周期性分析SMCA算法
查看>>
Linux下查看文件编码及批量修改编码
查看>>
大疆回应无人机数据安全风险质疑
查看>>
myeclipse格式化代码换行的问题
查看>>