【发布时间】:2020-09-18 11:31:09
【问题描述】:
我目前正在为一个方法创建单元测试。
这个应该测试的转换方法基本上由return if value > 0组成,所以我也想检查无符号溢出。
在为测试创建测试用例时,我偶然发现了 U 和 UL 后缀的这种非常特殊的行为。
[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
}
他们为什么会这样?它不应该只是溢出到uint 和ulong 的最大值吗?
我找不到任何答案。参考源似乎只包含包装对象 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