使用变量否定 'is' 运算符仅适用于 '!'但不是 '== false'
Negating the 'is' operator with a variable only works with '!' but not with '== false'
为什么(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'
}
编译器(还)不够聪明,无法发现这种情况:它不会将 == false
之类的因素纳入明确赋值分析。
然而,这 has been proposed 是由语言设计团队之一完成的(另请参阅此处的链接问题)。看起来他们目前正计划在 C# 10 中解决这个问题。
为什么(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'
}
编译器(还)不够聪明,无法发现这种情况:它不会将 == false
之类的因素纳入明确赋值分析。
然而,这 has been proposed 是由语言设计团队之一完成的(另请参阅此处的链接问题)。看起来他们目前正计划在 C# 10 中解决这个问题。