在 ulong 和 long 变量之间强制添加

Force addition between ulong and long variable

我有以下功能:

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# 编译器说我不能添加 ulonglongx 可以大于 long.MaxValue,而 min 可能为负。所以我不能把一个投给另一个。如何进行? :-(

learn casting 
example
ulong min=2;
ulong range = 12 - 2; // guaranteed to fit in ulong
ulong x = (ulong) range;
long we=  (long)x +(long) min;

    long.MinValue = -9223372036854775808
    long.MaxValue =  9223372036854775807
    18446744073709551615 <-- Max ulong
    0                    <-- Minulong

long can be negative and positive both.

    long range = long.MaxValue - 0; // guaranteed to fit in 
    long x = GenerateRandomLongBetween0AndRange(range);
`x= Math.Abs(x ) to get positive values if you are using long` for that.

Even your function is  ok  just change signature here

    long Foo (long min, long max)
    {
        ulong range = max - min; // guaranteed to fit in long
        ulong x = GenerateRandomULongBetween0AndRange(range);
        return (long) x +(long) min; // result is guaranteed to fit in long
    }

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 功能来确保即使有人打开 "checked by default" 也不会发生这种情况。