首页 > 其他 > 详细

【转载】#458 Errors While Converting Between enum and Underlying Type

时间:2014-03-21 04:25:38      阅读:448      评论:0      收藏:0      [点我收藏+]

You can convert to an enum value from its underlying type by casting the underlying type (e.g. int) to the enum type.

However, when you cast a value that doesn‘t have a corresponding enumerator in the type, you don‘t get any sort of error.

In the example below,the Mood type has enumerators that take on the values (0, 1, 2, 3). But we can successfully cast a value of 4 to the Mood type.

bubuko.com,布布扣
 1 public enum Mood { Crabby, Happy, Petulant, Elated };
 2 
 3 static void Main()
 4 {
 5     int moodValue = 4;
 6     Mood mood;
 7 
 8     mood = (Mood)moodValue;
 9     Console.WriteLine(mood);    // 4
10 }
bubuko.com,布布扣

To detect this problem, you can check to see if the value is defined in the enumerated type using the Enum.IsDefined method.

bubuko.com,布布扣
1 if (Enum.IsDefined(typeof(Mood), moodValue))
2  {
3     mood = (Mood)moodValue;
4  }
5 else
6 {
7     Console.WriteLine("{0} is not a valid Mood value!", moodValue);
8 }
bubuko.com,布布扣

原文地址:#458 Errors While Converting Between enum and Underlying Type

【转载】#458 Errors While Converting Between enum and Underlying Type,布布扣,bubuko.com

【转载】#458 Errors While Converting Between enum and Underlying Type

原文:http://www.cnblogs.com/yuthreestone/p/3614568.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!