本文介绍了枚举背后int的基本原理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 您好 花半小时搜索档案我还没有找到以下行为的理由 。 使用系统; //注意缺少的Flags属性 enum颜色 { 红色, 绿色, 蓝色 } 类无论如何 { 静态无效主要() { //以下演员成功虽然 //值42不存在。 颜色=(颜色)42; Console.WriteLine(" {0}",颜色); } } 我相信如果那个演员能够让我和其他人的生活变得更轻松> 失败。此外,该框架似乎甚至没有提供直接实现这一功能的功能 。我必须自己滚动,使用 Enum.IsDefined()。 这是什么理由? 谢谢&此致, Andreas 解决方案 只有当你经常从int转换为enum时,你不应该这样做b $ b无论如何都要做因为它打败了enum第一个 的地方。至少在调试模式下,编译器或框架应自动检查 该值是否实际有效。 再次,使用枚举而不是使用枚举的全部意义ints是类型安全的。 我同意Andreas的说法,这种行为很奇怪,应该是固定的,b / b是否有效。 - http://www.kynosarges.de Hi thereSpending half an hour searching through the archive I haven''t found arationale for the following behavior.using System;// note the missing Flags attributeenum Color{Red,Green,Blue}class Whatever{static void Main(){// The following cast succeeds although the// value 42 does not exist.Color color = (Color) 42;Console.WriteLine( "{0}", color );}}I believe it would make my and other peoples life easier if that castfailed. Moreover, the framework does not even seem to offer a functionto implement this directly. I have to roll my own, usingEnum.IsDefined().What is the rationale for this?Thanks & Regards,Andreas 解决方案Only if you constantly convert from int to enum which you shouldn''t bedoing anyway because it defeats the point of having enums in the firstplace. At least in debug mode, the compiler or framework should checkautomatically that the value is actually valid.Again, the whole point of using enums instead of ints is type safety.I agree with Andreas that this behaviour is bizarre and should befixed, performance hit or not.-- http://www.kynosarges.de 这篇关于枚举背后int的基本原理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!