c# 对枚举的反射


今天需要一个对枚举的反射,获取值和名称。

只需要这样:

 foreach (var item in Enum.GetValues(typeof(SignalFormat)))
            {
                Console.WriteLine(Convert.ToInt32(item) + "---->" + item.ToString());
            }

  item就是名称,将名称转换成int就是值。

 

还有一种方式

public static class AttributeHelper
    {
        public static string GetCustomAttributeValue(this DistributeTaskState em)
        {
            Type tp = em.GetType();
            object obj = Activator.CreateInstance(tp);
            List<string> list = new List<string>();
            foreach (var item in tp.GetFields())
            {
                if (item.IsDefined(typeof(RemarkAttribute), true))
                {
                    RemarkAttribute remarkAttribute = (RemarkAttribute)item.GetCustomAttribute(typeof(RemarkAttribute), true);
                    string val = item.GetRawConstantValue().ToString();//
                    string name = item.Name;//字段(键)
                    string v = item.ToString();
                    list.Add(remarkAttribute.GetRemark());
                    return remarkAttribute.GetRemark();
                }
            }

            return "";
        }
    }

上面这种方式是集合了特性和反射的。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM