在不强制转换的情况下对枚举使用 greater-than/less-than 运算符?

Using greater-than/less-than operator on enums without casting?

我不小心写了

if (myEnum1 < myEnum2)
{
   //do etc.
}

而且我没有遇到任何编译器错误。 我不应该先将这些枚举转换为它们的基础类型吗:

if ((int) myEnum1 < (int) myEnum2))
{
   //do etc.
}

这两个片段是否等价?我的IDE,Jetbrains Rider,好像不这么认为。我无法跳转到 < 定义,所以我假设它是一个编译器 thang'?

<><=>===!= 都是为所有枚举类型定义的 E:

bool operator ==(E x, E y);
bool operator !=(E x, E y);
bool operator <(E x, E y);
bool operator >(E x, E y);
bool operator <=(E x, E y);
bool operator >=(E x, E y);

这是在language specification中指定的。

他们的行为描述如下:

The result of evaluating x op y, where x and y are expressions of an enumeration type E with an underlying type U, and op is one of the comparison operators, is exactly the same as evaluating ((U)x) op ((U)y). In other words, the enumeration type comparison operators simply compare the underlying integral values of the two operands.

因此,如果枚举的基础类型为 int,那么您的两个代码片段将是相同的。