关于c#:当我们联系不存在的enum时,为什么我们不会得到异常?

Why don't we get an exception when we contact enum, which doesn't exist?

本问题已经有最佳答案,请猛点这里访问。

我很感兴趣,为什么这段代码不会给出异常,12356将输出到控制台?此行为枚举的含义是什么?

1
2
3
4
5
6
7
8
9
10
enum Dummy { D1 = 123, D2 = 1234, D3 }
class Program
{
     static void Main(string[] args)
     {
          Dummy d = (Dummy)12356;
          Console.WriteLine((int)d);
          Console.ReadKey();
     }
}

这是一个bug还是一个特性?


Is this a bug or a feature?

一个特性,尽管当代码不能按预期工作时,它可能会给您带来奇怪的情况。

例如,可以组合枚举值,例如:

1
2
3
enum Dummy { D1 = 1, D2 = 2, D3 = 4 }

Dummy v = Dummy.D1 | Dummy.D2;

这里的支持值是3。

您可以检查以下任一值:

1
bool isD1 = (v & Dummy.D1) == Dummy.D1;

您可以检查枚举的单值有效性,如下所示:

1
2
Dummy v = Dummy.D1;
bool isValid = Enum.IsDefined(typeof(Dummy), v);


这是设计上的,但不鼓励,如文件中所述:

It's possible to assign any arbitrary integer value to meetingDay. For
example, this line of code does not produce an error: meetingDay =
(Day) 42. However, you should not do this because the implicit
expectation is that an enum variable will only hold one of the values
defined by the enum. To assign an arbitrary value to a variable of an
enumeration type is to introduce a high risk for errors.

始终可以使用IsDefined检查给定值是否为枚举类型定义:

1
2
Console.WriteLine(Enum.IsDefined(typeof(Dummy), 123)); //True
Console.WriteLine(Enum.IsDefined(typeof(Dummy), 123456)); //False