铸造整数到枚举在C# [英] Casting ints to enums in C#

查看:133
本文介绍了铸造整数到枚举在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有东西,我不能在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;

编译器认为这很好。和运行时也。呃?

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#一个强类型语言,我想假设环保将永远持有合法颜色值。但这种情况并非如此。程序员可以调用我的方法分配给环保 17的值(如previous code段),所以在我的方法的code不要以为环保持有合法颜色值。我要明确地测试它,好像我处理例外值。这是为什么?

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?

在我的愚见,铸造一个超出范围时,它会好得多,如果编译器发出的错误(甚至是警告)消息 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"

在该 [国旗] 属性被放在枚举的前面,最后一行更改为

When the [Flags] attribute is put in front of the enum, that last line changes to

string text = ne.ToString();  // text == "North, East"

这篇关于铸造整数到枚举在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆