c# - 什么是 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
,但是有一些区别:
- 它可以与不可为空的类型一起使用,例如。
int
,而null
模式不能。 - 它可用于转换变量,例如
top is { } t
.
执行强制转换时,结果变量与初始变量的类型相同,但没有可空性,因此如果将其与int?
结果一起使用,则为int
:
int? nullable = 1;
if (nullable is { } nonNullable)
{
// nonNullable is int
}
当在语句{ }
中用作包罗万象时,该模式最有用:switch
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
}