遍歷枚舉類型心得


1.通過反射獲取枚舉字段時,第一個字段時系統帶的字段,類型是Int, Name貌似是_value.

需要過濾掉;

fi.FieldType == typeof(T);

或者

 if (fi.IsSpecialName) continue;

 

另外獲取Name, Value, Description

                string name = fi.Name;
                object value = Convert.ToInt32(fi.GetRawConstantValue());
                DescriptionAttribute[] descs = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
                var desc = descs.Length > 0 ? descs[0].Description : "";

                Console.WriteLine(string.Format("name:{0}; value:{1} ; des:{2}", name, value, desc));

 

另外,Enum中有個靜態方法,GetValues() 返回object[]  里面是name, 強轉int 可以獲得對應的value.

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM