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

只需要这样:

 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 "";
        }
    }

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

相关文章:

  • 2022-03-06
  • 2021-07-29
  • 2021-12-16
  • 2021-11-06
  • 2021-12-17
  • 2021-07-30
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-07-14
  • 2022-12-23
  • 2022-12-23
  • 2021-09-24
  • 2019-08-25
  • 2021-06-03
相关资源
相似解决方案