简体   繁体   English

Visual Studio 2015表示'演员是多余的'。为什么?

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

I have an image with width 888px and height 592px, with aspect ratio of width:height as 3:2. 我的图像宽度为888像素,高度为592像素,宽高比为3:2。

The following produces a wrong value of 1, because of integer calculation/truncation as BitmapDecoder.PixelWidth and BitmapDecoder.PixelHeight are both uint (unsigned integer), and decoder below being a BitmapDecoder object. 以下产生的错误值为1,因为整数计算/截断为BitmapDecoder.PixelWidth和BitmapDecoder.PixelHeight都是uint (无符号整数),而下面的decoder是BitmapDecoder对象。

double aspectRatio = decoder.PixelWidth / decoder.PixelHeight;

The following gives the expected correct value of 1.5, but Visual Studio says 'Cast is redundant', but why? 下面给出了1.5的预期正确值,但Visual Studio说“Cast是多余的”,但为什么呢?

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

You only need to cast one of the uints to double to force the floating point arithmetic so either: 您只需要将其中一个 uint强制转换为强制浮点运算,因此:

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

or: 要么:

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

Personally, I'd go with the latter, but it is a matter of opinion. 就个人而言,我会选择后者,但这是一个意见问题。

Just to complement @ChrisF's answer, you can see this nicely in the IL code, where a single cast to double will yield a conversion for both values: 只是为了补充@ 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM