【问题标题】:Visual Studio 2015: Invalid "Cast is redundant" warning in interpolated string expressionVisual Studio 2015:内插字符串表达式中的“强制转换是多余的”警告无效
【发布时间】:2015-08-25 14:38:52
【问题描述】:

考虑这个在 Visual Studio 2015 中编译良好的简单程序:

public class Program
{
    enum Direction
    {
        Up,
        Down,
        Left,
        Right
    }

    static void Main(string[] args)
    {
        // Old style
        Console.WriteLine(string.Format("The direction is {0}", Direction.Right));
        Console.WriteLine(string.Format("The direction is {0}", (int)Direction.Right));

        // New style
        Console.WriteLine($"The direction is {Direction.Right}");
        Console.WriteLine($"The direction is {(int)Direction.Right}");
    }
}

...按预期输出:

The direction is Right
The direction is 3
The direction is Right
The direction is 3

但是,Visual Studio 2015 一直在此行特别建议“快速操作”:

// "Cast is redundant" warning
Console.WriteLine($"The direction is {(int)Direction.Right}");

它坚持(int)“演员表是多余的”,并建议作为“删除不必要的演员表”的潜在解决方案,这当然是错误的,因为它会改变结果。

有趣的是,它没有给我任何等效语句的警告:

// No warnings.
Console.WriteLine(string.Format("The direction is {0}", (int)Direction.Right));

在插值字符串中使用表达式时,有人可以为这种误报提供合理的解释吗?

【问题讨论】:

    标签: c# casting visual-studio-2015 string-interpolation c#-6.0


    【解决方案1】:

    这是a known bug

    同时提出了一个临时解决方案:

    对于现在在 VS2015 中遇到此错误的人,解决方法是在受影响项目的属性页的构建选项卡中禁止警告 IDE0004。

    此问题已于 2015 年 9 月 9 日在 PR 5029 中修复并合并到 master 中。

    【讨论】:

      【解决方案2】:

      显式转换 在某种程度上是不必要的 - 您可以(并且可能应该)使用格式说明符:

      $"The direction is {Direction.Right:d}"
      

      但是,是的,警告是愚蠢的 - 它应该暗示这种变化,而不仅仅是删除 (int)。编译器有很多问题 - 幸运的是,大多数似乎都很容易解决。

      【讨论】:

      • 不知道你可以在枚举上使用 d 格式说明符而不先强制转换。感谢您的解决方法。当然,我没有在我的问题中提到这一点,但在我的现实世界问题中,我的字符串看起来更像这个$"The direction is {(int)Direction.Right:X8}"。所以我真的需要演员阵容,否则我会得到FormatException。不过这个很有用,谢谢!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-06
      • 1970-01-01
      相关资源
      最近更新 更多