【问题标题】:Meaning of curly braces after the "is" operator"is" 运算符后大括号的含义
【发布时间】:2020-09-20 04:57:06
【问题描述】:
我在一些 C# 源代码中发现以下行:
if(!(context.Compilation.GetTypeByMetadataName("Xunit.FactAttribute")
is { } factAttribute))
还有一个:
if(!(diagnostic.Location.SourceTree is { } tree))
is 运算符后面的花括号 ({ }) 是什么意思?
【问题讨论】:
标签:
c#
operator-keyword
curly-braces
c#-8.0
【解决方案1】:
这是 C# 8.0 中引入的新模式匹配功能,称为property pattern。在这种特殊情况下,它用于检查对象是否为空,来自链接文章的示例:
static string Display(object o) => o switch
{
Point { X: 0, Y: 0 } p => "origin",
Point { X: var x, Y: var y } p => $"({x}, {y})",
{} => o.ToString(),
null => "null"
};