Cha*_*rly 4 c# enums casting operator-overloading comparison-operators
我不小心写了
if (myEnum1 < myEnum2)
{
//do etc.
}
Run Code Online (Sandbox Code Playgroud)
并且我没有遇到编译器错误。我是否应该首先将这些枚举转换为它们的基础类型:
if ((int) myEnum1 < (int) myEnum2))
{
//do etc.
}
Run Code Online (Sandbox Code Playgroud)
这两个片段等效吗?我的 IDE Jetbrains Rider 似乎并不这么认为。我无法跳转到<定义,所以我假设它是一个编译器?
<、>、<=、>=和都是为所有枚举类型定义==的:!=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);
Run Code Online (Sandbox Code Playgroud)
这是语言规范中指定的。
他们的行为描述如下:
求值的结果与求值完全相同
x op y,其中x和是具有基础类型 的y枚举类型的表达式,并且是比较运算符之一。换句话说,枚举类型比较运算符只是比较两个操作数的基础整数值。EUop((U)x) op ((U)y)
因此,如果枚举的基础类型为 ,那么您的两个代码片段将是相同的int。