枚举类型转换成字符串
2012-06-22 23:27 JustRun 阅读(5322) 评论(1) 编辑 收藏 举报使用枚举类型默认的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 };
使用下面的方法,来得到对应项的字符串。
/// <summary> /// Contains methods for working with <see cref="Enum"/>. /// </summary> public static class EnumHelper { /// <summary> /// Gets the specified enum value's description. /// </summary> /// <param name="value">The enum value.</param> /// <returns>The description or <c>null</c> /// if enum value doesn't have <see cref="DescriptionAttribute"/>.</returns> 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; } /// <summary> /// Gets the enum value by description. /// </summary> /// <typeparam name="EnumType">The enum type.</typeparam> /// <param name="description">The description.</param> /// <returns>The enum value.</returns> public static EnumType GetValueByDescription<EnumType>(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."); } }
进一步了解.net中的Attribue

本文基于署名 2.5 中国大陆许可协议发布,欢迎转载,演绎或用于商业目的,但是必须保留本文的署名justrun(包含链接)。如您有任何疑问或者授权方面的协商,请给我留言。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· [AI/GPT/综述] AI Agent的设计模式综述