【腾讯云】云产品限时秒杀,爆款1核2G云服务器,首年99元

需要匹配的枚举描述

using System;
using System.ComponentModel;
namespace ConsoleApp1
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            var value = GetEnumValueByDescription("在读", typeof(StudentStatusEnum));
            Console.WriteLine(value.ToString());
            Console.ReadKey();
        }
        #region 根据枚举描述获取枚举值
        /// <summary>
        /// 根据枚举描述获取枚举值
        /// </summary>
        /// <param name="description">需要匹配的枚举描述</param>
        /// <param name="en">枚举类型</param>
        /// <returns></returns>
        public static object GetEnumValueByDescription(string description, Type en)
        {
            var fields = en.GetFields();
            for (int i = 1, count = fields.Length; i < count; i++)
            {
                var value = (int)Enum.Parse(en, fields[i].Name);
                var enumAttributes = (DescriptionAttribute[])fields[i].GetCustomAttributes(typeof(DescriptionAttribute), false);
                if (enumAttributes.Length > 0)
                {
                    var desc = enumAttributes[0].Description;
                    if (desc == description)
                    {
                        return value;
                    }
                }
            }

            return null;
        }
        #endregion
    }
    /// <summary>
    ///     学生状态
    /// </summary>
    public enum StudentStatusEnum
    {
        /// <summary>
        ///     在读
        /// </summary>
        [Description("在读")] Study = 0,
        /// <summary>
        ///     毕业
        /// </summary>
        [Description("毕业")] Graduate = 1,
        /// <summary>
        ///     退学
        /// </summary>
        [Description("退学")] Leave = 2,
        /// <summary>
        ///     休学
        /// </summary>
        [Description("休学")] Suspend = 3
    }
}

 

posted @ 2019-06-04 14:23  happenzh  阅读(366)  评论(0编辑  收藏  举报