在C#中,"{}"语法是什么意思? [英] What does 'is { }' syntax mean in c#?

查看:94
本文介绍了在C#中,"{}"语法是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在过去的两周里,我开始在C#中遇到这种新语法:

In the last couple of weeks I started encountering this new syntax in C#:

if (someObj is { })  
{    
    do some stuff 
}

因此它返回布尔值.似乎有点像JavaScript.但是,此检查的确切作用是什么?与此相同吗?

so it returns bool. It seems like JavaScript a little bit. But what exactly does this check do? Is it identical to this?

if (someObj == null)
{
    do some stuff
}

我知道C#的新版本包含很多语法糖.这部分吗?它有名字吗?例如,我知道?:被称为三元运算符,而?.被称为Elvis运算符.但是是{} 是什么?甚至是运算符吗?

I know that new versions of C# contain a lot of syntactic sugar. Is this part of that? Does it have some name or something? E.g., I know that ?: is called the ternary operator and ?. is called the Elvis operator. But what is is { }? Is it even an operator?

是的,在尝试在此处询问之前,我尝试过在线搜索,但由于请求中的括号,因此Google似乎拒绝找到与 is {} 语法有关的任何有用信息.

And yes, I've tried to search online before asking here, but it seems that Google refuses to find anything useful concerning the is { } syntax, because of the braces in the request.

推荐答案

从广义上讲,这是基于成员的模式匹配-例如:

In the more general sense, this is member-based pattern matching - for example:

if (foo is { Id: 42, Name: "abc"})
{

}

测试 foo 是否具有 Id 42和 Name "abc".在这种情况下,您正在测试零属性,因此它有效地 is object 相同(即,不是 null 的测试,或者是no-op true (用于非空值类型).

tests whether foo has Id 42 and Name "abc". In this case, you are testing zero properties, so it effectively becomes the same as is object (i.e. a not null test, or a no-op true for non-nullable value-types).

与问题中的内容进行比较( if(someObj == null))-它与该问题的相反,请注意,它也不会使用用于 null 测试的重载 == 运算符( == null 进行此测试).

To compare against what you have in the question (if (someObj == null)) - it is the opposite of that, noting that it will also not use an overloaded == operator for the null test (which == null will).

这篇关于在C#中,"{}"语法是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆