首先定义枚举类型,如下:

/// <summary>
/// 板块
/// </summary>
public enum Plate
{
        [Description("所有市场")]
        All = ,
        [Description("沪深300")]
        HS300 = ,
        [Description("创业板")]
        CYB = ,
        [Description("上证50")]
        SZ50 = ,
        [Description("中小板")]
        ZXB = ,
        [Description("中证500")]
        ZZ500 = ,
        [Description("包括指数")]
        BKZS = ,
 }

接下来是Helper类

public static class EnumHelper
{         /// <summary>
        /// 获取枚举值的Description
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string GetDescription<T>(this T value) where T : struct
        {
            string result = value.ToString();
            Type type = typeof(T);
            FieldInfo info = type.GetField(value.ToString());
            var attributes = info.GetCustomAttributes(typeof(DescriptionAttribute), true);
            if (attributes != null && attributes.FirstOrDefault() != null)
            {
                result = (attributes.First() as DescriptionAttribute).Description;
            }             return result;
   }         /// <summary>
        /// 根据Description获取枚举值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value"></param>
        /// <returns></returns>
        public static T GetValueByDescription<T>(this string description) where T : struct
        {
            Type type = typeof(T);
            foreach (var field in type.GetFields())
            {
                if (field.Name == description)
                {
                    return (T)field.GetValue(null);
                }                 var attributes = (DescriptionAttribute[])field.GetCustomAttributes(typeof(DescriptionAttribute), true);
                if (attributes != null && attributes.FirstOrDefault() != null)
                {
                    if (attributes.First().Description == description)
                    {
                        return (T)field.GetValue(null);
                    }
                }
            }             throw new ArgumentException(string.Format("{0} 未能找到对应的枚举.", description), "Description");
        }         /// <summary>
        /// 获取string获取枚举值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value"></param>
        /// <returns></returns>
        public static T GetValue<T>(this string value) where T : struct
        {
            T result;
            if (Enum.TryParse(value, true, out result))
            {
                return result;
            }             throw new ArgumentException(string.Format("{0} 未能找到对应的枚举.", value), "Value");
        }
    }

再给个EnumHelper类吧:

using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.ComponentModel;
using System.Web; namespace Vector.Framework.Tool
{
/// <summary>
/// 程序说明:枚举类型操作类
/// 建立者 :spw
/// 建立日期:2018-04-25
/// </summary>
public class EnumHelper
{
/// <summary>
/// 通过枚举类型得到集合
/// </summary>
/// <param name="type">集合类型</param>
/// <param name="hasAll">是否包含请选择</param>
/// <returns></returns>
public static List<ListItem> GetListItemByEnum(Type type, bool hasAll=true)
{
List<ListItem> list = new List<ListItem>();
FieldInfo[] fields = type.GetFields();
if (hasAll)
{
list.Add(new ListItem() { Value = "-1", Text = "请选择" });
} for (int i = , count = fields.Length; i < count; i++)
{
list.Add(new ListItem() { Value = ((int)Enum.Parse(type, fields[i].Name)).ToString(), Text = fields[i].Name });
}
return list;
} #region 枚举,值,串的相互转化
/// <summary>
/// 枚举转字符串
/// </summary>
/// <typeparam name="T">枚举类型</typeparam>
/// <param name="t">枚举对象</param>
/// <returns></returns>
private static string Enum2Text<T>(T t)
{
//string enumStringOne = color.ToString(); //效率低,不推荐
//string enumStringTwo = Enum.GetName(typeof(Color), color);//推荐
return Enum.GetName(typeof(T), t);
} /// <summary>
/// 枚举转值
/// </summary>
/// <typeparam name="T">枚举类型</typeparam>
/// <param name="t">枚举对象</param>
/// <returns></returns>
private static int Enum2Value<T>(T t)
{
//int enumValueOne = t.GetHashCode();
//int enumValueTwo = (int)color;
//int enumValueThree = Convert.ToInt32(color);
return t.GetHashCode();
} /// <summary>
/// 字符串转枚举
/// </summary>
/// <typeparam name="T">枚举类型</typeparam>
/// <param name="text">字符串</param>
/// <returns></returns>
private static T String2Enum<T>(string text)
{
//Color enumOne = (Color)Enum.Parse(typeof(Color), colorString);
return (T)Enum.Parse(typeof(T), text);
} /// <summary>
/// 字符串转值
/// </summary>
/// <typeparam name="T">枚举类型</typeparam>
/// <param name="text">字符串</param>
/// <returns></returns>
public static int String2Value<T>(string text)
{
//int enumValueFour = (int)Enum.Parse(typeof(Color), colorString);
return (int)Enum.Parse(typeof(T), text);
} /// <summary>
/// 值转枚举
/// </summary>
/// <typeparam name="T">枚举类型</typeparam>
/// <param name="value">值</param>
/// <returns></returns>
private static T Value2Enum<T>(int value)
{
//Color enumTwo = (Color)colorValue;
//Color enumThree = (Color)Enum.ToObject(typeof(Color), colorValue);
return (T)Enum.ToObject(typeof(T), value);
} /// <summary>
/// 值转字符串
/// </summary>
/// <typeparam name="T">枚举类型</typeparam>
/// <param name="value">值</param>
/// <returns></returns>
public static string Value2Text<T>(int value)
{
//string enumStringThree = Enum.GetName(typeof(Color), colorValue);
return Enum.GetName(typeof(T), value);
}
#endregion
} public class ListItem
{
/// <summary>
/// 显示值
/// </summary>
public string Text { get; set; }
/// <summary>
/// 实际值
/// </summary>
public string Value { get; set; }
/// <summary>
/// 是否选中
/// </summary>
public bool Selected { get; set; }
}
}

出处:https://blog.csdn.net/u011400752/article/details/83818832

https://blog.csdn.net/spw55381155/article/details/80074326

C# EnumHelper Enum的值,Description,ToString()的相互转换的更多相关文章

  1. C# Enum Name String Description之间的相互转换

    最近工作中经常用到Enum中Value.String.Description之间的相互转换,特此总结一下. 1.首先定义Enum对象 public enum Weekday { [Descriptio ...

  2. 获取Enum枚举值描述的几法方法

    原文:获取Enum枚举值描述的几法方法 1.定义枚举时直接用中文 由于VS对中文支持的很不错,所以很多程序员都采用了此方案. 缺点:1.不适合多语言 2.感觉不太完美,毕竟大部分程序员大部分代码都使用 ...

  3. Enum 枚举值 (一) 获取描述信息

    封装了方法: public static class EnumOperate { public class BaseDescriptionAttribute : DescriptionAttribut ...

  4. MVC3不能正确识别JSON中的Enum枚举值

    一.背景 在MVC3项目里,如果Action的参数中有Enum枚举作为对象属性的话,使用POST方法提交过来的JSON数据中的枚举值却无法正确被识别对应的枚举值. 二.Demo演示 为了说明问题,我使 ...

  5. C#遍历枚举(Enum)值

    foreach (object o in Enum.GetValues(typeof(EmpType))) { Console.WriteLine("{0}:{1}", o, En ...

  6. java enum 枚举值

    public enum PieChartEnum { PIE00("pie00"), PIE10("pie10"), PIE11("pie11&quo ...

  7. 从一个int值显示相应枚举类型的名称或者描述

    我正在做一个出入库管理的简单项目,在Models里定义了这样的枚举类型 public enum InOrOut { [Description("出库")] Out = , [Des ...

  8. Enum扩展及MVC中DropDownListFor扩展方法的使用

    public enum SearchState { /// <summary> /// 全部 /// </summary> [Description("全部" ...

  9. C# 枚举类型 enum

    我个人感觉平日用到的enum应该是非常简单的,无非就是枚举和整数.字符串之间的转换.最近工作发现一些同事居然不太会用这个东东,于是就整理一下. 枚举类型是定义了一组“符号名称/值”配对.枚举类型是强类 ...

随机推荐

  1. L1-059 敲笨钟

    微博上有个自称“大笨钟V”的家伙,每天敲钟催促码农们爱惜身体早点睡觉.为了增加敲钟的趣味性,还会糟改几句古诗词.其糟改的方法为:去网上搜寻压“ong”韵的古诗词,把句尾的三个字换成“敲笨钟”.例如唐代 ...

  2. python字符串常用操作

    #### 1) 判断类型 - 9 | 方法 | 说明 || --- | --- || string.isspace() | 如果 string 中只包含空格,则返回 True | | string.i ...

  3. websocket的属性readyState

    webSocket的readyState属性用来定义连接状态,该属性的值有下面几种: 0 :对应常量CONNECTING (numeric value 0), 正在建立连接连接,还没有完成.The c ...

  4. 酷学习笔记——ASP.NET Core 简介

    ASP.NET Core 简介 其实就是说酷好,不好好学,不学好,没饭吃. 新词汇:IoT,Internet of Things,网联网,微软物联网英文网站.微软物联网中文网站

  5. nginx——优化 Nginx 连接超时时间

    1. 什么是连接超时 (1) 举个例子,某饭店请了服务员招待顾客,但是现在饭店不景气,因此要解雇掉一些服务员,这里的服务员就相当于 Nginx 服务建立的连接 (2) 当服务器建立的连接没有接收处理请 ...

  6. Mybatis Generator主要配置详解

    MyBatis 的代码生成主要配置文档[具体] <?xml version="1.0" encoding="UTF-8"?> <!DOCTYP ...

  7. 在Linux系统使用VMware安装虚拟机

    首先到VMware官网上www.vmware.com下载相应的版本 我这边用的是 VMware-Workstation-Full-12.5.0-4352439.x86_64.bundle 上传到Lin ...

  8. Centos解除端口占用

    - 查看所有端口占用 - netstat -tln - 查看端口被哪个进程占用 - lsof -i:端口号 - 杀死被占用端口 - kill 端口号

  9. 封装qq分享静态库到cocopod

    封装qq分享静态库到cocopod  1,创建framework库,到腾讯开放平台(open.qq.com)申请项目appid 2,将iOS SDK中的TencentOpenAPI.framework ...

  10. 利用arcgis和envi对卫星图像按城市进行拼接,分割

    1.首先在envi中打开多波段原素材,右键点击另存为TIFF,输入保存的路径将原素材转换为tif格式图片. 2.之后打开arcgis,导入全国地区界数据,点击工具栏中的筛选工具. 输入查找的范围以及匹 ...