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