【发布时间】: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'
}
【问题讨论】:
-
@RaceRalph 它不计算如果 o 不是
string,它将return和s不会用于Console.WriteLine的事实。他们没有预先计算将要使用的代码路径 -
使用 C# 9,如果有帮助,您可以使用
if (o is not string s) return;。如果它不分支到return语句,则s肯定已分配且非空。 -
为什么是因为还没建。下一个问题
标签: c# .net compiler-errors operators