C# - meaning of curly braces after the “is” operator

痞子三分冷 提交于 2020-12-20 20:07:32

问题


I found in some C# source code the following line:

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

and here is another one:

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

What is the meaning of the curly braces ({ }) after the is operator?


回答1:


This is a new pattern matching feature which was introduced in C# 8.0 and is called property pattern. In this particular case it is used to check that object is not null, example from linked article:

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"
};


来源:https://stackoverflow.com/questions/62139886/c-sharp-meaning-of-curly-braces-after-the-is-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!