【问题标题】:Visual Studio 2015 says the 'cast is redundant'. Why?Visual Studio 2015 说“演员表是多余的”。为什么?
【发布时间】:2016-03-06 13:44:51
【问题描述】:

我有一个宽度为 888 像素,高度为 592 像素的图像,宽高比为 3:2。

由于整数计算/截断,以下生成错误值 1,因为 BitmapDecoder.PixelWidth 和 BitmapDecoder.PixelHeight 都是 uint(无符号整数),而 decoder 下面是 BitmapDecoder 对象。

double aspectRatio = decoder.PixelWidth / decoder.PixelHeight;

以下给出了预期的正确值 1.5,但 Visual Studio 说“演员表是多余的”,但为什么呢?

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

【问题讨论】:

  • 你只需要一个(双)演员 - double / int = double。或 int / double = double。
  • 如果用任何数字类型除以双精度数,结果将始终是双精度数。
  • double aspectRatio = static_cast<double>(decoder.PixelWidth) / decoder.PixelHeight; 应该足以让编译器使用 PixelHeight 作为双精度。
  • 为了绝对准确,我希望 Visual Studio 在必要时不理会第一个演员表,而只将第二个演员表渲染为多余的。从这个意义上说,Visual Studio 有点误导,但可以解释(或争论)原因。
  • 这和C++有什么关系?

标签: c# visual-studio-2015 uwp


【解决方案1】:

您只需要将 一个 的 uint 转换为 double 以强制浮点运算,因此:

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

或:

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

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

【讨论】:

  • 得到它!一个演员就足够了,但 Visual Studio 让我偏离了轨道。我希望 Visual Studio 不理会第一个演员表,而只将第二个演员表渲染为不必要的绝对准确。从这个意义上说,Visual Studio 有点误导,但可以解释原因。
【解决方案2】:

为了补充@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)

【讨论】:

    猜你喜欢
    • 2015-10-23
    • 1970-01-01
    • 2011-07-13
    • 2013-01-30
    • 2015-10-31
    • 1970-01-01
    • 2012-10-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多