遍歷枚舉類型心得

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

須要過濾掉;code

fi.FieldType == typeof(T);

或者

 if (fi.IsSpecialName) continue;

 

另外獲取Name, Value, Descriptionorm

                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.blog

相關文章
相關標籤/搜索