C# 反射获取枚举

枚举

using System.ComponentModel;

namespace Common.BaseEnum
{
    /// 
    /// 测试枚举
    /// 
    public enum TestEnum
    {
        /// 
        /// 测试1
        /// 
        [Description("测试1")]
        Test1 = 1,
        /// 
        /// 测试2
        /// 
        [Description("测试2")]
        Test2 = 2,
        /// 
        /// 测试1
        /// 
        [Description("测试3")]
        Test3 = 3,
    }
}

反射

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;

namespace EnumTest
{
    class Program
    {
        static void Main(string[] args)
        {
            //加载目标程序集Common.dll
            string CommonAssembly =
                "Common, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
            Assembly assembly = Assembly.Load(CommonAssembly);

            List> StatusEnumList =
                new List>();
            //反射枚举(namespace.enum)
            Type type = assembly.GetType("Common.BaseEnum.TestEnum");
            foreach (var item in Enum.GetValues(type))
            {
                var attrs = item.GetType().GetField(item.ToString())
                    .GetCustomAttributes(typeof(DescriptionAttribute), true);
                string desc = string.Empty;
                if (attrs != null && attrs.Length > 0)
                {
                    DescriptionAttribute descAttr = attrs[0] as DescriptionAttribute;
                    desc = descAttr.Description;
                }
                KeyValuePair keyValuePair =
                    new KeyValuePair(Convert.ToInt32(item), desc);
                StatusEnumList.Add(keyValuePair);
            }
        }
    }
}

你可能感兴趣的:(c#,C#,反射,枚举)