为什么我被告知这种类型转换是多余的?

Lor*_*tel 3 c# resharper

方程式很简单,int = int * int / int; 然而,整数的乘法可能会变得太大,我试图Int64在执行之前将所有内容都强制转换为s,然后将结果转换回int.因此我有:

int = (int)((Int64)int * (Int64)int / (Int64)int);
Run Code Online (Sandbox Code Playgroud)

并且它抱怨所有三个Int64演员阵容.

注意:目标是x86,因为我使用的是32位库. 机器本身是64位.我可以用x64目标来理解它.

  • 我错过了什么吗?
  • Resharper不理解中间值溢出的问题吗?

Din*_*esh 5

Int16 a = 1000;
Int16 b = 40;

var c = a * b; // c is Int32 because compiler does not want overflow

// The cast makes a3 Int64
// No need to cast a1 because all operations involving Int64
// will be Int64 to ensure no overflows when arithmetic operations are performed
var a3 = a1 * (Int64)a2; 
Run Code Online (Sandbox Code Playgroud)

同样的:

var a3 = (Int64)a1 * a2;
Run Code Online (Sandbox Code Playgroud)

如你所知,Resharper很聪明,它会为你代码中的所有3个演员提供警告,因为其中任何一个演员都有同感.

编辑:还有一件事,右边的所有操作都被评估,并且在完成1次投射后输出为Int64.最终的int cast将对最终计算的值起作用,并且它显式转换为int,因为Int64不能直接转换为int(防止溢出).没有中间值溢出.