问题描述
我当前正在为一种方法创建单元测试。
本应测试的convert方法基本上由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
,并且其中不包含任何运算符。
注意:我知道首先这样做是没有意义的。我只是发现这种行为非常意外。
解决方法
似乎正在将uint转换为long,以便总是有足够的位来存储产生的正值和负值的整个潜在范围。无法将-运算符应用于ulong,因为没有更大的类型可以将其转换为