我有以下功能:
long Foo (long min, long max)
{
ulong range = max - min; // guaranteed to fit in ulong
ulong x = GenerateRandomULongBetween0AndRange(range);
return x + min; // result is guaranteed to fit in long
}
但是 C# 编译器说我不能添加 ulong
和 long
。不过,x
可以大于 long.MaxValue
,并且 min
可能为负数。所以我不能把一个投给另一个。如何进行? :-(
最佳答案
The C# compiler says I cannot add ulong and long.
正确。
x can be greater than long.MaxValue though, and min may be negative.
正确。
So I can't cast one to the other.
不正确。投他们。走着瞧吧!您可能会感到惊喜。
long/ulong算术没有区别;位模式完全相同,并且编译成相同的代码。只是对不同位的解释。
一个警告:当涉及整数运算的溢出时,可以将 C# 置于崩溃的模式,并且您明确不希望它在此处崩溃。通过在其表达式或语句形式中使用 unchecked
功能,您可以确保即使有人打开“默认选中”也不会发生这种情况。
关于c# - 在 ulong 和 long 变量之间强制添加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52449293/