【问题标题】:Meaning of curly braces after the "is" operator\"is\" 运算符后大括号的含义
【发布时间】:2021-11-05 22:56:53
【问题描述】:

我在一些 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"
    };
    

    【讨论】:

    • 它是否与使用not null 模式相同?我知道空括号允许我们为这个模式创建一个别名,但我不确定我们是否不需要别名。
    • @anuith 是的,确实如此。如果您不需要别名,则应该可以互换使用两者。
    猜你喜欢
    • 2020-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多