【问题标题】:Weird behavior of -1U and -1UL [duplicate]-1U 和 -1UL 的奇怪行为 [重复]
【发布时间】:2020-09-18 11:31:09
【问题描述】:

我目前正在为一个方法创建单元测试。

这个应该测试的转换方法基本上由return if value > 0组成,所以我也想检查无符号溢出。

在为测试创建测试用例时,我偶然发现了 UUL 后缀的这种非常特殊的行为。

[DataTestMethod]
// more data rows
[DataRow(-1U, true)] // Technically compiles, but not to what I expected or "wanted"
[DataRow(-1UL, true)] // "CS0023: Operator '-' cannot be applied to operand of type 'ulong'"
// more data rows
public void TestConvertToBool(object value, bool result)
{
    // For testing purposes
    ulong uLong = -1UL; // "CS0023: Operator '-' cannot be applied to operand of type 'ulong'"
    uint uInt = -1U; // "CS0266: Cannot implicitly convert type 'long' to 'uint'. An explicit conversion exists (are you missing a cast?) - Cannot convert source type 'long' to target type 'uint'"
    var foo = -1U; // foo is of type 'long'
    var bar = 1U; // bar is of type 'uint'

    // ... do the actual assertion here
}

他们为什么会这样?它不应该只是溢出到uintulong 的最大值吗?

我找不到任何答案。参考源似乎只包含包装对象 UInt32 并且不包含任何运算符。

注意:我知道一开始这样做并没有真正的意义。我只是发现这种行为非常出乎意料。

【问题讨论】:

  • U 代表无符号,定义负数 unsigned 没有意义。您可以将负符号转换为无符号,即useful
  • @Sinatr 就像我说的,我知道这没有意义。我只是好奇它为什么会这样。我也知道unsigned是什么意思,所以我说Shouldn't it just overflow to the max values of uint and ulong?
  • 如果您知道将数字实现为 2s 补码数字的外观,则使其溢出是有意义的。从语言设计的角度来看,这可以被视为您不应该向程序员公开的实现细节。

标签: c# compiler-errors type-conversion long-integer uint


【解决方案1】:

似乎它将 uint 转换为 long 以便始终有足够的位来存储产生的正值和负值的整个潜在范围。 - 运算符不能应用于 ulong,因为没有更大的类型可以将其转换为

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-13
    • 2014-07-29
    相关资源
    最近更新 更多