码迷,mamicode.com
首页 > 其他好文 > 详细

C#根据描述获取枚举

时间:2020-10-27 10:52:34      阅读:25      评论:0      收藏:0      [点我收藏+]

标签:枚举   eof   throw   foreach   course   object   tom   return   col   

        /// <summary>
        /// 根据描述获取枚举值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="description"></param>
        /// <returns></returns>
        public static T GetEnumByDescription<T>(string description) where T : Enum
        {
            System.Reflection.FieldInfo[] fields = typeof(T).GetFields();
            foreach (System.Reflection.FieldInfo field in fields)
            {
                object[] objs = field.GetCustomAttributes(typeof(DescriptionAttribute), false);    //获取描述属性
                if (objs.Length > 0 && (objs[0] as DescriptionAttribute).Description == description)
                {
                    return (T)field.GetValue(null);
                }
            }

            throw new ArgumentException(string.Format("{0} 未能找到对应的枚举.", description), "Description");
        }

根据描述获取枚举

/// <summary>
        /// 根据枚举值,获取描述
        /// </summary>
        /// <param name="enumValue"></param>
        /// <returns></returns>
        public static string GetEnumDes(Enum enumValue)
        {
            string value = enumValue.ToString();
            FieldInfo field = enumValue.GetType().GetField(value);
            object[] objs = field.GetCustomAttributes(typeof(DescriptionAttribute), false);    //获取描述属性
            if (objs == null || objs.Length == 0)    //当描述属性没有时,直接返回名称
                return value;
            DescriptionAttribute descriptionAttribute = (DescriptionAttribute)objs[0];
            return descriptionAttribute.Description;
        }

根据枚举返回描述

namespace zxx
{
    /// <summary>
    /// 订单类型
    /// </summary>
    public enum OrderType
    {
        /// <summary>
        /// 订金
        /// </summary>
        [Description("订金")]
        Pre,
        /// <summary>
        /// 学费
        /// </summary>
        [Description("学费")]
        TutionFee,
        /// <summary>
        /// 课程费差价
        /// </summary>
        [Description("课程费差价")]
        CourseFee,
        /// <summary>
        /// 附加服务
        /// </summary>
        [Description("附加服务")]
        Addtional,
        /// <summary>
        /// 成绩单
        /// </summary>
        [Description("成绩单")]
        Transcript,
    }
}

C#根据描述获取枚举

标签:枚举   eof   throw   foreach   course   object   tom   return   col   

原文地址:https://www.cnblogs.com/gzbit-zxx/p/13877065.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!