有时我会看到以下代码,并且不知道该表达式实际上正在测试什么。
public static void Something(string[] value)
{
if (value is { })
{
DoSomethingElse();
}
}
答案 0 :(得分:30)
这只是C#8中的空属性模式,意味着值不是null
。它与任何值类型或引用类型匹配。正如Panagiotis Kanavos在评论中指出的那样,这等效于很好的旧value is object
检查,它已经在C#中使用了很长时间了。
通常,如果要指定一个属性,则该属性是否匹配。这个深奥的例子说明了:
if (value is { Length: 2 })
{
// matches any object that isn't `null` and has a property set to a length of 2
}
在诸如switch
表达式的情况下,与其他模式进行比较时,属性模式最有效,最清晰。
答案 1 :(得分:8)
虽然丹尼尔的答案是正确的,但我认为添加一些关于为什么的上下文可能会很有用,因为您可能会看到使用中的空属性模式。考虑需要完成一些验证的示例控制器方法:
public function store(CreatePostsRequest $request)
{
$image= $request->image->store('posts');
Post::create([
'title'=>$request->title,
'description'=>$request->description,
'content'=> $request->content,
'image'=> $image
]);
session()->flash('success','Post Created Successfully.');
return redirect(route('posts.index'));
}
在上面,public async Task<IActionResult> Update(string id, ...)
{
if (ValidateId(id) is { } invalid)
return invalid;
...
}
可以返回null或ValidateId()
的实例。如果返回前者,则验证成功,并继续进行到BadObjectRequestResult
正文的其余部分。如果返回后者,则Update
为 true (即is {}
的实例当然为BadObjectRequestResult
),并且验证失败。
很妙的是,除此之外,我们还提供了一个变量名object
,我们可以立即返回它。否则,我们将需要更多详细代码。
invalid
无论是可读性强还是由读者决定,我只是介绍了一种使用空属性模式的方法。
答案 2 :(得分:0)
我认为是要检查该值是否为空对象