考虑以下乍一看很荒谬的模式匹配:
string s = null;
if (s is string ss) //false
if (s is string) //false
两者 is
都会返回 false
。但是,如果我们使用 var
,行为就会完全改变:
string s = null;
if (s is var ss) //true!?!
如果在 VS2017 中将鼠标悬停在 var
上,类型是 string
但 的行为是
完全不同的。即使推断的类型相同,编译器也会做一些完全不同的事情。怎么会这样?这是一个错误吗? null
类型是否以某种方式冒出?
最佳答案
C# 语言引用确认行为是有意的。
A pattern match with the var pattern always succeeds. Its syntax is
expr is var varname
Where the value of expr is always assigned to a local variable named varname. varname is a static variable of the same type as expr.
Note that if expr is null, the is expression still is true and assigns null to varname.
Source: MSDN - C# Language Reference
var
模式
var 模式只是将源变量复制到一个新的命名变量中,然后您可以像下面这样构建一个 case block 表达式
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
关于c# - 使用 var 或显式类型时模式匹配的不同行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45904000/