遍历枚举类型心得


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