什么是C#对象模式匹配



我知道C#中的模式匹配类似于:

if (x is TypeY y)
{
// do thing...
}

或多或少等同于:

if (x is TypeY)
{
var y = (TypeY)x;
// do thing...
}

但是,我在编写IntelliSense建议的代码时发现了一些东西。我有以下代码:

if (top is { } t)
{
// do stuff if 'top' is NOT NULL
}

起初,我以为我可以做if (top is not null t),但我做不到;然后我转到if (top is int t),也就是在那时我提出了这个建议。这是什么意思?它是如何工作的?我只在switch语句中的模式匹配方面见过它,比如:

class Point
{
public int X { get; set; }
public int Y { get; set; }
}
myPoint switch
{
{ X: var x, Y: var y } when x > y => ...,
{ X: var x, Y: var y } when x <= y => ...,
...
};

但是,即使这是一个相当新的概念,我也不太熟悉更先进的概念。这与我的问题有关吗?

is { }is not null大致等效,但有几个区别:

  1. 它可以与不可为null的类型一起使用,例如int,而null模式不能
  2. 它可以用于强制转换变量,例如top is { } t

执行强制转换时,生成的变量与初始变量的类型相同,但不可为空,因此如果将其与int?一起使用,结果将为int:

int? nullable = 1;
if (nullable is { } nonNullable)
{
// nonNullable is int
}

{ }模式在switch语句中用作catch-all时最有用:

abstract class Car { }
class Audi : Car { }
class BMW : Car { }
// Other car types exist..
Car? car = //...
switch (car)
{
case Audi audi: // Do something with an Audi
case BMW bmw: // Do something with a BMW
case { } otherCar: // Do something with a non-null Car
default: // car is null
}

最新更新