使用变量否定“is”运算符仅适用于“!” 但不是 '== false'

Ziv*_*ivS 6 .net c# compiler-errors operators

为什么(expr is type varname) == false会出现编译错误,但可以!(expr is type varname)编译?

public static void Foo(object o)
{
    if(!(o is string s))  // <-- Using '!'
    {
        return;
    }
    
    Console.WriteLine(s);  // <-- OK
    
}
public static void Bar(object o)
{
    if((o is string s) == false) // <-- Using '== false'
    {
        return;
    }
    
    Console.WriteLine(s);  // <--Error: Use of unassigned local variable 's'
}
Run Code Online (Sandbox Code Playgroud)

现场示例:https : //dotnetfiddle.net/nYF7b6

can*_*on7 6

编译器(还)不够聪明,无法发现这种情况:它不会将诸如== false确定分配分析之类的因素考虑在内。

然而,这由语言设计团队之一提出的(另请参阅那里的相关问题)。看起来他们目前正计划在 C# 10 中涵盖这一点。