C# 8.0 中是否有针对非空的“检查并获取”运算符?

gre*_*man 3 c# nullable c#-8.0

至于检查类型,我们有一个运算符,它可以同时有效地执行两件事:

if (GetObject() is DateTimeOffset dto)
{
   // use dto here
}
Run Code Online (Sandbox Code Playgroud)

在这个例子中不仅dto是特定类型DateTimeOffset,而且该值是本地的并且被完全评估。

那么,C# 8.0 是否提供了类似的运算符来检查非空值?

if (GetPossibleNull() is not null x)
{
  // x is local, evaluated and guaranteed to be not-null
}
Run Code Online (Sandbox Code Playgroud)

Pre*_*soc 5

您可以使用空属性模式 ( {}) 来检查变量是否不是null

if (GetPossibleNull() is {} x)
{
  // x is local, evaluated and guaranteed to be not-null
}
Run Code Online (Sandbox Code Playgroud)