#458 Errors While Converting Between enum and Underlying Type

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.

 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 }

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

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 }

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

你可能感兴趣的:(convert)