这个模式匹配表达式是否等价于not null

man*_*ale 3 c# syntax

我在 github 上偶然发现了这段代码

if (requestHeaders is {})
Run Code Online (Sandbox Code Playgroud)

我不明白它到底做了什么。

经过试验,它似乎只有在 requestHeaders 为空时才为假。

这只是写的另一种方式if (requestHeaders != null)if (!(requestHeaders is null))

ven*_*mit 5

C#中的模式匹配支持属性模式匹配。例如

if (requestHeaders  is HttpRequestHeader {X is 3, Y is var y})
Run Code Online (Sandbox Code Playgroud)

属性模式的语义是它首先测试输入是否为非空。所以它允许你写:

if (requestHeaders is {}) // will check if object is not null
Run Code Online (Sandbox Code Playgroud)

您可以使用以下任何一种方式编写相同的类型检查,以提供Not Null包含的检查:

if (s is object o) ... // o is of type object
if (s is string x) ... // x is of type string
if (s is {} x) ... // x is of type string
if (s is {}) ...
Run Code Online (Sandbox Code Playgroud)

在这里阅读更多

  • 是否有任何理由使用此模式而不是 if (!= null) ? (2认同)