这是怎么回事?如果否则”声明称为?
我有时在我的代码中使用这种 if
:
!Value == null ? DoSomething : DoSomethingElse;
我想知道这样的 if else
语句的正确名称是什么。
另外,我想知道同一结构中是否只能有一个 if
部分,而没有 else
。
i sometimes use this kind of if
in my code:
!Value == null ? DoSomething : DoSomethingElse;
and i was wondering what is the proper name for an if else
statement like that.
also, i wonder if there can only be a if
part, without the else
in the same structure.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
它称为条件运算符。它是一个三元运算符(也是唯一的一个),但这并不是它的名字。
您不能像使用 if 语句那样使用它。您只能在需要它返回两个值之一的地方使用它。这两个值必须是相同的类型,或者它们之间需要存在隐式转换。
It's called a conditional operator. It is a ternary operator (and the only one), but that's not what it's called.
You can't use it as you can use an if statement. You can only use it where you need it to return one of two values. The two values need to be the same type, or an implicit conversion needs to exist between them.
回答你的第二个问题:
答案是“有点”,如果你想检查是否为空,这称为空合并。语法类似,如下所示:
如果值不为空,则返回左侧,如果为空,则返回右侧。
To answer your second question:
The answer is 'kind of', if you want to check for a null, which is called a null coalesce. The syntax is similar and goes like this:
What this does is return the left hand side if the value is not null and if it is null, return the right.
它被称为三元运算符,它的工作原理就像...
如果值不为空(正如您添加的那样!),则执行某些操作(DoSomething 将被调用。否则,(意味着如果条件失败),则执行其他操作(DoSomethingElse 将被调用)称为)。
Its' called ternary operator and it works like...
If value is not null (as you have added !) then do something (DoSomething will be called. Else, (means if the codition fails), then do something else (DoSomethingElse will be called).