C#中的枚举ints枚举 [英] Casting ints to enums in C#
问题描述
int
转换为枚举
,编译器不会退出。想象一下这个枚举
: 枚举颜色
{
红色= 1,
绿色= 2,
蓝色= 3
}
现在,如果你写:
Color eco;
eco =(颜色)17;
编译器认为没关系。而运行时也是如此。呃?
为什么C#团队决定让这个成为可能?这个决定错过了使用枚举的点,我认为在这样的场景中:
void DoSomethingWithColour(Color eco)
{
//做某事去生态。
}
在类似C#的强类型语言中,我想假设 eco
将始终保持合法的颜色
值。但事实并非如此。程序员可以调用我的方法,值为17,分配给 eco
(如以前的代码片段),所以我的方法中的代码不能假定 eco
持有合法的颜色
值。我需要明确地测试它,并处理我特别的价值。为什么是这样?
在我谦虚的意见中,如果编译器在投射超出范围时发出错误(甚至是警告)消息会更好, code> int into 枚举
,如果 int
编译时间。如果没有,运行时应该在赋值语句中抛出异常。
你觉得怎么样?有没有理由这样做?
(注意:这是一个问题我在几年前发布在我的博客上,但没有提供任何信息回复。)
枚举方向{北= 1,东= 2,南= 4,西= 8}
方向ne = Direction.North | Direction.East;
int value =(int)ne; // value == 3
string text = ne.ToString(); // text ==3
当 [Flags] code>属性放在枚举的前面,最后一行更改为
string text = ne.ToString( ); // text ==North,East
There is something that I cannot understand in C#. You can cast an out-of-range int
into an enum
and the compiler does not flinch. Imagine this enum
:
enum Colour
{
Red = 1,
Green = 2,
Blue = 3
}
Now, if you write:
Colour eco;
eco = (Colour)17;
The compiler thinks that’s fine. And the runtime, too. Uh?
Why did the C# team decide to make this possible? This decision misses the point of using enums, I think, in scenarios like this:
void DoSomethingWithColour(Colour eco)
{
//do something to eco.
}
In a strong-typed language like C#, I would like to assume that eco
will always hold a legal Colour
value. But this is not the case. A programmer could call my method with a value of 17 assigned to eco
(as in previous code snippet), so the code in my method must not assume that eco
holds a legal Colour
value. I need to test for it explicitly and handle the exceptional values as I please. Why is this?
In my humble opinion, it would be much nicer if the compiler issued an error (or even a warning) message when casting an out-of range int
into an enum
, if the int
value is known at compile time. If not, the runtime should throw an exception at the assignment statement.
What do you think? Is there any reason why this is so?
(Note. This is a question I posted ages ago on my blog but got no informative response.)
Guessing about 'why' is always dangerous, but consider this:
enum Direction { North =1, East = 2, South = 4, West = 8 }
Direction ne = Direction.North | Direction.East;
int value = (int) ne; // value == 3
string text = ne.ToString(); // text == "3"
When the [Flags]
attribute is put in front of the enum, that last line changes to
string text = ne.ToString(); // text == "North, East"
这篇关于C#中的枚举ints枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!