C# - “is”运算符后面的大括号的含义

Das*_*San 7 c# curly-braces operator-keyword

我在一些 C# 源代码中发现了以下行:

if(!(context.Compilation.GetTypeByMetadataName("Xunit.FactAttribute") is { } factAttribute))

这是另一个:

if(!(diagnostic.Location.SourceTree is { } tree))

运算符{ }后面的花括号 ( )是什么意思is

Gur*_*ron 9

这是 C# 8.0 中引入的新模式匹配功能,称为属性模式。在这种特殊情况下,它用于检查对象是否为空,例如来自链接文章:

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"
};
Run Code Online (Sandbox Code Playgroud)