遍历枚举类型心得

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.

 

 

 

posted @ 2014-03-12 00:04  Jimmy wu  阅读(3818)  评论(0编辑  收藏  举报