-1U和-1UL的怪异行为

问题描述

我当前正在为一种方法创建单元测试。

本应测试的convert方法基本上由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,并且其中不包含任何运算符。

注意:我知道首先这样做是没有意义的。我只是发现这种行为非常意外。

解决方法

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

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...