Tim*_*uin 1 c# casting pattern-matching
我知道 C# 中的模式匹配类似于:
if (x is TypeY y)
{
// do thing...
}
Run Code Online (Sandbox Code Playgroud)
这或多或少相当于:
if (x is TypeY)
{
var y = (TypeY)x;
// do thing...
}
Run Code Online (Sandbox Code Playgroud)
但是,我在编写 IntelliSense 建议的代码时发现了一些东西。我有以下代码:
if (top is { } t)
{
// do stuff if 'top' is NOT NULL
}
Run Code Online (Sandbox Code Playgroud)
本来我以为我能做到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 => ...,
...
};
Run Code Online (Sandbox Code Playgroud)
但是,即使这是相当新的,我也不太熟悉更先进的概念。这与我的问题有关吗?
is { }大致相当于is not null,但是,有一些区别:
int,而null模式则不能。top is { } t。执行强制转换时,结果变量与初始变量的类型相同,但不能为空,因此如果将其与结果一起使用,int?结果将是int:
int? nullable = 1;
if (nullable is { } nonNullable)
{
// nonNullable is int
}
Run Code Online (Sandbox Code Playgroud)
{ }当在语句中用作包罗万象时,该模式最有用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
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
729 次 |
| 最近记录: |