c# - 使用 var 或显式类型时模式匹配的不同行为

标签 c#

考虑以下乍一看很荒谬的模式匹配:

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/

相关文章:

c# - Windows Phone 8记录来自麦克风C#的声音

c# - Json 列 SQL

c# - SlimDX Direct3D11 中的线框

c# - ReadOnlySequence<byte> 解析

c# - 背靠背 for 循环中的 int、short、byte 性能

c# - 异步任务<IActionResult> 与任务<T>

c# - 为什么在 StreamReader.Read 周围使用 using() {} 允许之后删除文件?

c# - 关于 C# 中 Math.Round 的简单问题

c# - 符号已创建,但调试永远不会在断点处停止

c# - 在 Unity 中使用动态关键字/.NET 4.6 功能