简体   繁体   English

Visual Studio 2015:插值字符串表达式中的“Cast is redundant”警告无效

[英]Visual Studio 2015: Invalid “Cast is redundant” warning in interpolated string expression

Consider this simple program which compiles fine in Visual Studio 2015: 考虑一下这个在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}");
    }
}

... which outputs as expected: ...按预期输出:

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

However, Visual Studio 2015 keeps suggesting a "Quick Action" on this line specifically: 但是,Visual Studio 2015特别建议在此行中建议“快速操作”:

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

It insists that the (int) "cast is redundant" , and suggests as a potential fix to "Remove Unnecessary Cast" , which of course is wrong, as it would change the result. 它坚持认为(int) “演员是多余的” ,并建议作为“删除不必要的演员”的潜在修复,这当然是错误的,因为它会改变结果。

Interestingly, it doesn't give me any warning for the equivalent statement: 有趣的是,它没有给我任何相应声明的警告:

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

Can someone provide a reasonable explanation for this false-positive when using an expression in an interpolated string? 当在插值字符串中使用表达式时,有人能为这种误报提供合理的解释吗?

This is a known bug . 这是一个已知的错误

A temporary fix has been proposed for the mean time: 已经提出了一个临时修复的平均时间:

For people experiencing this bug in VS2015 now, a workaround is to suppress warning IDE0004 in the build tab of the property pages of the affected project. 对于现在在VS2015中遇到此错误的人,解决方法是在受影响项目的属性页的构建选项卡中禁止警告IDE0004。

This has been fixed and merged into master on 09/09/2015 in PR 5029 . 这已经修复并于2015年9月9日在PR 5029合并为主人。

The explicit cast is unnecessary in a way - you can (and probably should) use a format specifier: 显式转换在某种程度上不必要的 - 您可以(并且可能应该)使用格式说明符:

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

But yeah, the warning is silly - it should suggest this change, not just removing (int) . 但是,是的,警告是愚蠢的 - 它应该建议这种改变,而不仅仅是删除(int) The compiler has quite a few kinks - fortunately, most seem to be very easy to work around. 编译器有很多问题 - 幸运的是,大多数似乎很容易解决。

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

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