Visual Studio 2015 表示'cast is redundant'。为什么?

Visual Studio 2015 says the 'cast is redundant'. Why?

我有一张宽 888px 高 592px 的图片,宽高比 width:height 为 3:2。

下面产生错误的值 1,因为整数 calculation/truncation 因为 BitmapDecoder.PixelWidth 和 BitmapDecoder.PixelHeight 都是 uint(无符号整数),而 decoder 下面是一个 BitmapDecoder 对象。

double aspectRatio = decoder.PixelWidth / decoder.PixelHeight;

下面给出了1.5的预期正确值,但是Visual Studio说的是'Cast is redundant',但是为什么呢?

double aspectRatio = (double)decoder.PixelWidth / (double)decoder.PixelHeight;

您只需将 一个 uint 强制转换为 double 即可强制执行浮点运算,因此:

double aspectRatio = decoder.PixelWidth / (double)decoder.PixelHeight;

或:

double aspectRatio = (double)decoder.PixelWidth / decoder.PixelHeight;

就我个人而言,我会选择后者,但这是一个见仁见智的问题。

只是为了补充@ChrisF 的回答,您可以在 IL 代码中很好地看到这一点,其中对 double 的单个强制转换将产生两个值的转换:

IL_0013:  stloc.0     // decoder
IL_0014:  ldloc.0     // decoder
IL_0015:  callvirt    UserQuery+Decoder.get_PixelHeight
IL_001A:  conv.r.un   // convert uint to float32
IL_001B:  conv.r8     // convert to float64 (double)
IL_001C:  ldloc.0     // decoder
IL_001D:  callvirt    UserQuery+Decoder.get_PixelWidth
IL_0022:  conv.r.un   // convert uint to float32
IL_0023:  conv.r8     // convert to float64 (double)