преобразование int -> enum
От: Vasvasvas2004  
Дата: 12.04.10 19:39
Оценка:
Вопрос 1.
enum ETest{ One = 1, Two = 2};
...

ETest oETestOne = (ETest) 1;
ETest oETestTwo = (ETest) 2;
ETest oETestSomething = (ETest) 3;


Компилируется. Программа проходит все 3 строчки без проблем. Дебаггер показывает

oETestOne = "One"
oETestTwo = "Two"
oETestSomething ="3"

Хотелось бы получить Exception с "3".

Вопрос 2.
enum ETest{ One = 1, Two = 2};
...

ETest oETestSomething = (ETest) 2.2;

В данном случае компилятор ругается.
Но вот читаю стандарт вот отсюда http://www.ecma-international.org/publications/standards/Ecma-334.htm

============
8.11 Enums
...
The use of enums is superior to the use of integer constants
...
============
Компилятор кажется ругается по делу!

============
13.2.2 Explicit enumeration conversions
The explicit enumeration conversions are:
• From sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, or decimal to
any enum-type.
• From any enum-type to sbyte, byte, short, ushort, int, uint, long, ulong, char, float,
double, or decimal.
• From any enum-type to any other enum-type.
An explicit enumeration conversion between two types is processed by treating any participating enum-type
as the underlying type of that enum-type, and then performing an implicit or explicit numeric conversion
between the resulting types. [Example: Given an enum-type E with and underlying type of int, a conversion
from E to byte is processed as an explicit numeric conversion (§13.2.1) from int to byte, and a
conversion from byte to E is processed as an implicit numeric conversion (§13.1.2) from byte to int. end
example]
===========

А что!!! А вроде легко должен преобразовывать! Надо только поменять underlying type. Как это сделать?
 
Подождите ...
Wait...
Пока на собственное сообщение не было ответов, его можно удалить.