简体   繁体   English

三元运算符如何工作?

[英]How does the ternary operator work?

Please demonstrate how the ternary operator works with a regular if/else block.请演示三元运算符如何与常规 if/else 块配合使用。 Example:示例:

Boolean isValueBig = value > 100 ? true : false;

Exact Duplicate: How do I use the ternary operator?完全重复: 如何使用三元运算符?

Boolean isValueBig = ( value > 100  ) ? true : false;


Boolean isValueBig;

if(  value > 100 ) { 
      isValueBig = true;
} else { 
     isValueBig = false;
}

The difference between the ternary operation and if/else is that the ternary expression is a statement that evaluates to a value, while if/else is not.三元运算与 if/else 的区别在于,三元表达式是求值结果的语句,而 if/else 则不是。

To use your example, changing from the use of a ternary expression to if/else you could use this statement:要使用您的示例,从使用三元表达式更改为 if/else 您可以使用以下语句:

Boolean isValueBig = null;
if(value > 100)
{ 
    isValueBig = true 
}
else
{
    isValueBig = false;
}

In this case, though, your statement is equivalent to this:但是,在这种情况下,您的语句等效于:

Boolean isValueBig = (value > 100);

When I was new to C++, I found that it helped to read this construct as follows:当我刚接触 C++ 时,我发现它有助于阅读以下构造:

Boolean isValueBig = if condition ? then x else: y;

(Notice that this isn't valid code. It's just what I trained myself to read in my head.) (请注意,这不是有效代码。这只是我训练自己在脑海中阅读的内容。)

Boolean isValueBig;

if (value > 100)
{
   isValueBig = true;
}
else 
{
   isValueBig = false;
}

I was never a fan of the ternary operator because I thought it was hard to read.我从来不是三元运算符的粉丝,因为我认为它很难阅读。 As it so happens, Jon Skeet and his book, C# in Depth finally hit this old dog over the head and got it to sink in. Jon said, and I paraphrase, think of it as a question.碰巧的是,Jon Skeet 和他的书, C# in Depth最终击中了这只老狗的头,让它沉入其中。Jon 说,我解释说,把它当作一个问题。

value > 100?值 > 100?

"yes" : "no" “是”:“否”

Now the blind can see.现在盲人可以看见了。

Hope this helps you make it second nature.希望这可以帮助您使其成为第二天性。

Boolean isValueBig;

if(value > 100) { isValueBig = true; } else { isValueBig = false; }

As quoted from the ?: Operator MSDN page , "the conditional operator (?:) returns one of two values depending on the value of a Boolean expression."正如引用自?: Operator MSDN page ,“条件运算符 (?:) 根据布尔表达式的值返回两个值之一。”

So you can use the ternary operator to return more than just booleans:因此,您可以使用三元运算符返回的不仅仅是布尔值:

   string result = (value > 100 ) ? "value is big" : "value is small";

PHP Example PHP 示例

<?php

  // Example usage for: Ternary Operator
  $action = (empty($_POST['action'])) ? 'default' : $_POST['action'];

  // The above is identical to this if/else statement
  if (empty($_POST['action'])) {
    $action = 'default';
  } else {
    $action = $_POST['action'];
  }

?>

"The expression (expr1) ? (expr2) : (expr3) evaluates to expr2 if expr1 evaluates to TRUE , and expr3 if expr1 evaluates to FALSE ." “表达式(表达式1)(表达式2):(表达式3)的计算结果为表达式2如果expr1的评估为,并且如果表达式3 expr1的评估为”。

PHP Documentation on Comparison Operators 关于比较运算符的 PHP 文档

Bad example, because you could easily write不好的例子,因为你可以很容易地写

Boolean isValueBig = value > 100 ? true : false;

as:如:

bool isValueBig = value > 100

Beyond that, everyone else has already answered it.除此之外,其他人都已经回答了。 I would just not recommend using ternary operators to set bool values, since what you are evaluating is already a boolean value.我只是不建议使用三元运算符来设置 bool 值,因为您正在评估的已经是一个布尔值。

I realize it was just an example, but it was worth pointing out.我意识到这只是一个例子,但值得指出。

Make sure you don't mix types in true/false parts in Java.确保不要在 Java 中的真/假部分混合类型。 It produces weird results :-(它产生奇怪的结果:-(

Others have answered it already but here's one thing you should really know about ternary's usage and by that I mean don't ever do it.其他人已经回答了它,但是关于三元的用法,您应该真正了解一件事,我的意思是永远不要这样做。

Lets assume that you have a piece of code which is supposed to return a different object for each possible variation of some value, lets say for simpliticy's sake an integer between 1 and 5. Your code looks like this:让我们假设你有一段代码,它应该为某个值的每个可能的变化返回一个不同的对象,为了简单起见,我们假设一个 1 到 5 之间的整数。你的代码如下所示:

if(i==1) {
    return new ObjectOne();
} else if(i==2) {
    return new ObjectTwo();
} else if(i==3) {
    return new ObjectThree();
} else if(i==4) {
    return new ObjectFour();
} else if(i==5) {
    return new ObjectFive();
} else {
    return new DefaultObject();
}

It's easy to understand but a bit heavy.这很容易理解,但有点沉重。 Since ternary is just another way of writing an if..else statement that can be refactored to this由于三元只是编写 if..else 语句的另一种方式,可以重构为

return (i==1) ? new ObjectOne() :
       (i==2) ? new ObjectTwo() :
       (i==3) ? new ObjectThree() :
       (i==4) ? new ObjectFour() :
       (i==5) ? new ObjectFive() : new DefaultObject();

It's called nested ternary .它被称为嵌套三元 It's evil, now that you know about it please never use it.这是邪恶的,既然你知道了,请永远不要使用它。 It may seem to have its uses like the case above but it's very likely that in real life situations you would need to use it somewhere where it loses readability (think altering configurations with variable amount of parameters and such).它的用途似乎与上面的情况类似,但很可能在现实生活中,您需要在失去可读性的地方使用它(考虑使用可变数量的参数更改配置等)。

Bonus sector: Never set attribute values inside if(), just look at this: if(bool=true!=false) { .. }奖励部门:永远不要在 if() 中设置属性值,看看这个: if(bool=true!=false) { .. }

As quoted from MSDN (noted in a previous post)引用自 MSDN(在前一篇文章中提到)

string result = (value > 100 ) ?字符串结果 = (值 > 100 ) ? "value is big" : "value is small"; "价值大" : "价值小";

Could be read as:可以读作:

Is value greater than 100?值是否大于 100? If yes, string result is "value is big", if no, string result is "value is small".如果是,字符串结果是“值大”,如果不是,字符串结果是“值小”。

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

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