使用var或显式类型时,模式匹配中的不同行为 [英] Different behavior in pattern matching when using var or explicit type
问题描述
乍看之下,模式匹配应考虑以下内容:
Consider the following, at first glance absurd, pattern match:
string s = null;
if (s is string ss) //false
if (s is string) //false
两个 is
都将返回 false
.但是,如果我们使用 var
,则行为会完全改变:
Both is
will return false
. However if we use var
the behavior changes completely:
string s = null;
if (s is var ss) //true!?!
如果将鼠标悬停在 VS2017 中的 var
上,则类型为 string
,但是 is
的行为完全是不同的.即使推断的类型相同,编译器也会做一些根本不同的事情.怎么会这样?这是一个错误吗? null
类型是否会冒泡?
If you hover over var
in VS2017, the type is string
but the behavior of is
is completely different. The compiler is doing something radically different even though the inferred type is the same. How can this be? Is this a bug? Is the null
type somehow bubbling out?
推荐答案
C#语言参考确认行为是预期的.
The C# language reference confirms the behaviour is intended.
与var模式匹配的模式总是成功的.它的语法是
A pattern match with the var pattern always succeeds. Its syntax is
expr is var varname
expr的值始终分配给名为的局部变量varname.varname是与expr类型相同的静态变量.
请注意,如果expr为空,则is表达式仍为true,并将空值分配给varname.
Note that if expr is null, the is expression still is true and assigns null to varname.
var模式只是将源变量复制到一个新的命名变量中,然后您可以使用以下代码构建一个case块表达式
The var pattern just copies the source variable into a new named variable which you can then build a case block expression with like below
string s = null;
var collection = new string[] { "abb", "abd", "abc", null};
switch (s)
{
case "xyz":
Console.WriteLine("Is xyz");
break;
case var ss when (collection).Contains(s):
Console.WriteLine("Is in list");
break;
default:
Console.WriteLine("Failed!");
break;
}
输出:
> Is in list
这篇关于使用var或显式类型时,模式匹配中的不同行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!