在 C# 中将整数转换为枚举 [英] Casting ints to enums in C#

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

问题描述

在 C# 中有一些我无法理解的东西.您可以将超出范围的 int 转换为 enum 并且编译器不会退缩.想象一下这个enum:

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# 这样的强类型语言中,我想假设 eco 将始终保持合法的 Colour 值.但这种情况并非如此.程序员可以使用分配给 eco 的值 17 调用我的方法(如在前面的代码片段中),因此我的方法中的代码不能假定 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?

以我的拙见,如果编译器在将超出范围的 int 转换为 enum,如果 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# 中将整数转换为枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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