【问题标题】:Negating the 'is' operator with a variable only works with '!' but not with '== false'用变量否定“is”运算符仅适用于“!”但不是'== false'
【发布时间】:2021-05-10 21:20:39
【问题描述】:

为什么(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'
}

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

【问题讨论】:

  • @RaceRalph 它不计算如果 o 不是 string,它将 returns 不会用于 Console.WriteLine 的事实。他们没有预先计算将要使用的代码路径
  • 使用 C# 9,如果有帮助,您可以使用 if (o is not string s) return;。如果它不分支到return 语句,则s 肯定已分配且非空。
  • 为什么是因为还没建。下一个问题

标签: c# .net compiler-errors operators


【解决方案1】:

编译器(还)不够聪明,无法发现这种情况:它不会将== false 之类的东西纳入明确的赋值分析中。

这个has been proposed 由语言设计团队之一提供(另请参阅那里的链接问题)。看起来他们目前正计划在 C# 10 中涵盖这一点。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-27
    • 1970-01-01
    • 2021-02-25
    • 1970-01-01
    • 2017-01-06
    • 1970-01-01
    相关资源
    最近更新 更多