简体   繁体   English

返回否定的布尔值时,“ Cast是多余的”警告

[英]“Cast is redundant” warning when returning negated bool

The following program compiles fine in Visual Studio 2015 Update 2, but a "Cast is redundant" warning is generated: 以下程序在Visual Studio 2015 Update 2中可以正常编译,但是会生成“投射过多”警告:

class Program
{
    static void Main(string[] args)
    {
        Program p = new Program();
        bool negated = p.NegateBool(true);
    }

    public bool NegateBool(object value)
    {
        // "Cast is redundant" warning.
        return !(bool)value;

        // No warning.
        //return (bool)value;

        // No warning.
        //var negated = !(bool)value;
        //return negated;
    }
}

When accepting the "Quick Fix" suggestion to remove the cast, the program no longer compiles. 当接受“快速修复”建议以删除演员表时,该程序将不再编译。

This is only happening when the cast is done directly in the return statement and the negation operator is used. 仅当直接在return语句中执行强制转换并使用求反运算符时,才会发生这种情况。

If the result is put into a variable and then returned, no warning is generated. 如果将结果放入变量中然后返回,则不会生成警告。

Does anyone know why this is happening? 有人知道为什么会这样吗?

This was a bug in the Roslyn compiler. 这是Roslyn编译器中的错误。

I have filed a bug report on Github and the problem will be fixed in a future version: 我已经在Github上提交了错误报告,该问题将在以后的版本中修复:
https://github.com/dotnet/roslyn/issues/10311 https://github.com/dotnet/roslyn/issues/10311

bool negated = p.NegatedBool(true); 否定的布尔值= p.NegatedBool(true);

compiler already knows that you are passing and boolean at this point. 编译器已经知道此时您正在传递布尔值。 try truee instead of true and it will give you an error. 尝试用true代替true,这会给你一个错误。 and if you type true compiler knows that its a boolean from system.boolean , just hover your mouse over true. 如果您输入true,则编译器会从system.boolean得知它是布尔值,只需将鼠标悬停在true上即可。 so now the compiler already knows that its an bool. 所以现在编译器已经知道它是布尔值。 just put a debug point on your methods first line. 只需在方法的第一行上放置一个调试点即可。 thats the opening curly brace , and go to debug. 多数民众赞成在开头花括号,并进行调试。 if your add a watch on value you will know it may show something like this object{bool} in its type. 如果您添加值监视功能,您将知道它可能在其类型中显示类似此对象{bool}的内容。

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

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