简体   繁体   English

“是{}”是什么意思?

[英]What does "is { }" mean?

I see the following code sometimes, and have no idea what the expression is actually testing.我有时会看到以下代码,但不知道该表达式实际在测试什么。

public static void Something(string[] value)
{
   if (value is { })
   {
      DoSomethingElse();
   }
}

That's just the empty property pattern in C# 8, meaning the value not null .这只是 C# 8 中的空属性模式,这意味着值不为null It matches any value type or reference type.它匹配任何值类型或引用类型。 As Panagiotis Kanavos notes in the comments, this is equivalent to the good old value is object check which has been in C# for a long time.正如 Panagiotis Kanavos 在评论中指出的那样,这相当于在 C# 中使用了很长时间的旧value is object check。

Generally if you were to specify a property, then it would match or not.通常,如果您要指定一个属性,则它会匹配或不匹配。 This esoteric example illustrates that:这个深奥的例子说明了:

if (value is { Length: 2 })
{
   // matches any object that isn't `null` and has a property set to a length of 2
}

The property patterns work best and are most clear when comparing with other patterns in cases such as switch expressions.在与switch表达式等情况下的其他模式进行比较时,属性模式效果最好,也最清晰。

While Daniel's answer is right, I think it might be useful to add some context about why you may see the empty property pattern in use.虽然 Daniel 的回答是正确的,但我认为添加一些关于为什么您可能会看到正在使用的空属性模式的上下文可能会很有用。 Consider this example controller method that needs some validation done:考虑这个需要完成一些验证的示例控制器方法:

public async Task<IActionResult> Update(string id, ...) 
{
    if (ValidateId(id) is { } invalid)
        return invalid;
    ...
}

In the above, ValidateId() could return null or an instance of BadObjectRequestResult .在上面, ValidateId()可以返回 null 或BadObjectRequestResult的实例。 If the former is returned, the validation is successful and moves on to the rest of the body of Update .如果返回前者,则验证成功并移至Update主体的其余部分。 If the latter is returned, is {} is true (ie of course an instance of BadObjectRequestResult is an object ), and the validation fails.如果返回后者, is {}(即BadObjectRequestResult的实例当然是一个object ),验证失败。

Nicely, out of this we've also provided a variable name, invalid , which we can return immediately.很好,除此之外,我们还提供了一个变量名invalid ,我们可以立即返回它。 Without that we'd need slightly more verbose code.没有它,我们将需要稍微冗长的代码。

public async Task<IActionResult> Update(string id, ...) 
{
    var invalid = ValidateId(id);
    if (invalid != null)
        return invalid;
    ...
}

Whether one is more readable or the other is up to the reader, I've just presented one way the empty property pattern can be used.无论一种更易读还是另一种取决于读者,我刚刚介绍了一种可以使用空属性模式的方式。

我认为是检查值是否为空对象

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM