c#枚举的描述和值

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication15
{
    class Program
    {

    
        public static string FetchDescription(Enum value)
        {
            FieldInfo fi = value.GetType().GetField(value.ToString());
            DescriptionAttribute[] attributes =
               (DescriptionAttribute[])fi.GetCustomAttributes(
               typeof(DescriptionAttribute), false);
            return (attributes.Length > 0) ? attributes[0].Description : value.ToString();
        }

        static void Main(string[] args)
        {
            TestEnum testEnum = TestEnum.one;
          
            // 获取枚举的描述          
            string thisValue = FetchDescription(testEnum);
            //获取枚举的值
            var val = (int)testEnum;

        }

    }


    public enum TestEnum
    {
        [Description("大家好我是描述")]
        one = 1,
        two = 2,
        three = 3
    }
}

 

posted on 2018-05-03 11:42  花生哒哒  阅读(187)  评论(0编辑  收藏  举报

导航