至于检查类型,我们只有一个运算符,它有效地同时做两件事:
if (GetObject() is DateTimeOffset dto)
{
// use dto here
}
此示例中的dto
不仅属于特定类型DateTimeOffset
,而且该值是本地的,并且经过完全评估。
那么,C# 8.0 是否提供了类似的运算符来检查非空值?
if (GetPossibleNull() is not null x)
{
// x is local, evaluated and guaranteed to be not-null
}
您可以使用空的属性模式 ({}
( 来检查变量是否未null
if (GetPossibleNull() is {} x)
{
// x is local, evaluated and guaranteed to be not-null
}
x is T y
表达式还会检查所有类型(引用类型和Nullable<T>
(的null
值,即使x
已经静态类型化为T
- 这适用于 C# 7.0:
class Foobar {}
static Foobar GetPossibleNull() { return null; }
static void Main()
{
if( GetPossibleNull() is Foobar foobar )
{
Console.WriteLine( "GetPossibleNull() returned a non-null value." );
}
else
{
Console.WriteLine( "GetPossibleNull() returned null." );
}
}
当我运行这个程序时,我在控制台窗口中看到"GetPossibleNull(( 返回 null"。
这些变体在 C# 7.3 中也按预期工作(我现在无法访问 C# 8.0 编译器(:
static Nullable<Int32> GetNullInt32() => null;
static Nullable<Int32> GetNonNullInt32() => 123;
static void Main()
{
if( GetNullInt32() is Int32 nonNullInt )
{
Console.WriteLine( "GetNullInt32() returned a non-null value." );
}
else
{
Console.WriteLine( "GetNullInt32() returned null." );
}
if( GetNonNullInt32() is Int32 nonNullInt )
{
Console.WriteLine( "GetNonNullInt32() returned a non-null value." );
}
else
{
Console.WriteLine( "GetNonNullInt32() returned null." );
}
}
输出:
GetNullInt32() returned null.
GetNonNullInt32() returned a non-null value.