【发布时间】:2011-05-18 16:19:31
【问题描述】:
您可以在 sbyte 和 byte、int、uint、short、ushort、long、double 和 float 之间进行 >、
我的大脑正在爆炸。谁能解释为什么 sbyte 可以与 uint 进行比较,但 不是 ulong?
public bool sbyte_ulong_compare(sbyte x, ulong y)
{
return x < y; // compiler error CS0019
}
此外,使用unchecked 并不会让事情变得更好。大脑融化。
另一个编辑。这有效:
public bool sbyte_ulong_compare(sbyte x, ulong y)
{
//
// returns x < y
//
if (x < 0)
return true;
if (y > 127)
return true;
return ((long)x < (long)y);
}
【问题讨论】:
-
好问题!但是,对于我们这些没有尝试过的人,当你尝试比较时会发生什么?您以什么方式不能比较这些类型(抛出异常、无法编译等...)?
-
@djacobson:编译器吐出
Operator '==' cannot be applied to operands of type 'sbyte' and 'ulong'至少它在 .NET 3.5 项目中的 VS2k8 中是这样。 -
我加了一个短代码sn-p。
-
回复:
unchecked- 假设 this 是您所指的关键字,它会抑制溢出检查,与无效的布尔比较无关。 -
@djacobson:是的。我想,嗯,也许魔法会发生。 :(