【转载】#458 Errors While Converting Between enum and Underlying Type
2014-03-20 20:36
555 查看
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.
To detect this problem, you can check to see if the value is defined in the enumerated type using the Enum.IsDefined method.
原文地址:#458 Errors While Converting Between enum and Underlying 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.
public enum Mood { Crabby, Happy, Petulant, Elated }; static void Main() { int moodValue = 4; Mood mood; mood = (Mood)moodValue; Console.WriteLine(mood); // 4 }
To detect this problem, you can check to see if the value is defined in the enumerated type using the Enum.IsDefined method.
if (Enum.IsDefined(typeof(Mood), moodValue)) { mood = (Mood)moodValue; } else { Console.WriteLine("{0} is not a valid Mood value!", moodValue); }
原文地址:#458 Errors While Converting Between enum and Underlying Type
相关文章推荐
- 【转载】#457 Converting Between enums and their Underlying Type
- Resolving Http 500 Server Errors in ASP.Net and IIS 5.1(转载)
- Python---TypeError: '<' not supported between instances of 'str' and 'int'
- Errors while installing OpenCV2.3.1 and FFMPEG Ubuntu
- Python3.6:“猜数字游戏”TypeError: '<' not supported between instances of 'str' and 'int'
- Type I and type II errors | 第一类错误和第二类错误
- Mapping type between C++ and C#
- 译 Programming with typesafe enums and annotations in Java 5
- 【转载】#446 - Deciding Between an Abstract Class and an Interface
- Recipe 1.2. Converting Between Characters and Numeric Codes(Python Cookbook)
- Difference between RegularEnumSet and JumboEnumSet in Java
- Effective C#之6:Distinguish Between Value Type and Reference Type
- 转载:How can I drag and drop items between data bound ItemsControls?
- the difference between isinstance and type in python
- 转载:How to create an automation project using MFC and a type library
- How to: Handle Data Conflicts and Errors 【转载】
- Boost问题:/type_with_alignment.hpp:209: Parenthesis/brace mismatch between #if and #else branches;
- While installing plugin in eclipse luna, “Unable to acquire PluginConverter service” and “No repository found” errors appear in logs
- SharePoint : The difference and relation between SPListItem.Update and SPListItem.SystemUpdate Methods 【转载】
- Converting Between Binary and Decimal in C#