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

时间:2012-12-25 04:48:49

标签: c# resharper

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

int = (int)((Int64)int * (Int64)int / (Int64)int);

并且它抱怨所有三个Int64演员。

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

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

3 个答案:

答案 0 :(得分: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; 

同样的:

var a3 = (Int64)a1 * a2;

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

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

答案 1 :(得分:3)

第一个演员阵容产生了Int64。 Int64 * int是Int64。除以int是Int64。

答案 2 :(得分:0)

施放其中一个就足够了

int x, y, z, w;
x = y = z = int.MaxValue;

查看下面的行为,你会理解这一切

textBox1.Text = ((Int64)x * y).ToString();

输出:4611686014132420609

textBox2.Text = (x * y).ToString();

输出:1

textBox3.Text = ((int)((Int64)x * (Int64)y / (Int64)z)).ToString();

输出:2147483647

相关问题