问题描述
有些东西我在C#中不能理解。你可以将一个超出范围的 int
转换为枚举
,编译器不会退缩。想象这个枚举
:
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
}
现在,如果你写:
Colour eco;
eco = (Colour)17;
编译器认为这很好。和运行时,太。 Uh?
The compiler thinks that’s fine. And the runtime, too. Uh?
为什么C#团队决定这么做?这个决定错过了使用枚举的点,我认为,在这样的场景:
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.
}
在像C#这样的强类型语言中, code> eco 将始终保持合法的颜色
值。但事实并非如此。程序员可以调用我的方法,值为17分配给 eco
(如前面的代码片段),因此我的方法中的代码不能假设 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?
根据我的拙见,如果编译器发出错误(甚至警告)消息, code> int 到枚举
,如果 int
编译时间。如果没有,运行时应该在赋值语句中抛出异常。
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"
当 [Flags]
属性放在枚举前面,最后一行更改为
When the [Flags]
attribute is put in front of the enum, that last line changes to
string text = ne.ToString(); // text == "North, East"
这篇关于在C#中枚举int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!