三元运算符如何工作?

发布于 2024-07-12 22:31:33 字数 259 浏览 8 评论 0原文

请演示三元运算符如何与常规 if/else 块一起使用。 示例:

Boolean isValueBig = value > 100 ? true : false;

精确重复: 如何使用三元运算符?

Please demonstrate how the ternary operator works with a regular if/else block. Example:

Boolean isValueBig = value > 100 ? true : false;

Exact Duplicate: How do I use the ternary operator?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(13

只是一片海 2024-07-19 22:31:33
Boolean isValueBig = ( value > 100  ) ? true : false;

// above line is same as:

Boolean isValueBig;

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

// above line is same as:

Boolean isValueBig;

if(  value > 100 ) { 
      isValueBig = true;
} else { 
     isValueBig = false;
}
清引 2024-07-19 22:31:33

三元运算和 if/else 之间的区别在于,三元表达式是计算结果的语句,而 if/else 不是。

要使用您的示例,从使用三元表达式更改为 if/else,您可以使用以下语句:

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

不过,在这种情况下,您的语句等效于:

Boolean isValueBig = (value > 100);

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.

To use your example, changing from the use of a ternary expression to if/else you could use this statement:

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);
只涨不跌 2024-07-19 22:31:33

当我刚接触 C++ 时,我发现它有助于阅读以下结构:(

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

请注意,这不是有效的代码。这只是我训练自己在脑海中阅读的内容。)

When I was new to C++, I found that it helped to read this construct as follows:

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.)

鹿童谣 2024-07-19 22:31:33
Boolean isValueBig;

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

if (value > 100)
{
   isValueBig = true;
}
else 
{
   isValueBig = false;
}
初雪 2024-07-19 22:31:33

我从来不喜欢三元运算符,因为我认为它很难阅读。 碰巧的是,Jon Skeet 和他的书《C# 深度剖析》终于击中了这只老狗的头,让他明白了。Jon 说,我转述一下,把它看作一个问题。

值> 100?

“是”:“否”

现在盲人可以看见了。

希望这可以帮助您使其成为第二天性。

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.

value > 100?

"yes" : "no"

Now the blind can see.

Hope this helps you make it second nature.

飘逸的'云 2024-07-19 22:31:33
Boolean isValueBig;

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

if(value > 100) { isValueBig = true; } else { isValueBig = false; }
少女情怀诗 2024-07-19 22:31:33

正如?:运营商 MSDN 页面引用 ,“条件运算符 (?:) 根据布尔表达式的值返回两个值之一。”

因此,您可以使用三元运算符返回的不仅仅是布尔值:

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

As quoted from the ?: Operator MSDN page, "the conditional operator (?:) returns one of two values depending on the value of a Boolean expression."

So you can use the ternary operator to return more than just booleans:

   string result = (value > 100 ) ? "value is big" : "value is small";
酸甜透明夹心 2024-07-19 22:31:33

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'];
  }

?>

“如果 expr1 计算结果为 TRUE<,则表达式 (expr1) ? (expr2) : (expr3) 计算结果为 expr2 /strong>,如果 expr1 计算结果为 FALSE,则 expr3。”


比较运算符的 PHP 文档

PHP Example

<?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."

PHP Documentation on Comparison Operators

百合的盛世恋 2024-07-19 22:31:33

确保不要在 Java 中混合正确/错误部分的类型。 它会产生奇怪的结果:-(

Make sure you don't mix types in true/false parts in Java. It produces weird results :-(

水溶 2024-07-19 22:31:33

不好的例子,因为你可以很容易地写成

Boolean isValueBig = value > 100 ? true : false;

bool isValueBig = value > 100

除此之外,其他人都已经回答了。 我只是不建议使用三元运算符来设置布尔值,因为您正在评估的已经是布尔值。

我意识到这只是一个例子,但值得指出。

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.

I realize it was just an example, but it was worth pointing out.

小傻瓜 2024-07-19 22:31:33

其他人已经回答了这个问题,但是您应该真正了解三元用法的一件事,我的意思是永远不要这样做。

假设您有一段代码,它应该为某个值的每个可能变化返回一个不同的对象,为了简单起见,我们假设返回一个 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();
}

很容易理解,但有点重的。 由于三元只是编写 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();

嵌套三元。 它是邪恶的,既然你知道它,请永远不要使用它。 它的用途可能类似于上面的情况,但在现实生活中,您很可能需要在失去可读性的地方使用它(考虑使用可变数量的参数等来更改配置)。

奖励部分:永远不要在 if() 内设置属性值,只需看一下: if(bool=true!=false) { .. }

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:

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

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) { .. }

娇妻 2024-07-19 22:31:33

正如 MSDN 中引用的那样(在上一篇文章中指出)

string result = (value > 100 ) ? "价值大" : "价值小";

可以理解为:

值是否大于 100? 如果是,则字符串结果为“值大”,如果否,则字符串结果为“值小”。

As quoted from MSDN (noted in a previous post)

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

Could be read as:

Is value greater than 100? If yes, string result is "value is big", if no, string result is "value is small".

穿透光 2024-07-19 22:31:33

三元运算符来自函数范式。 为了证明这一点,在 smlnj 中举了一个例子:

fun ternary(cond, trueVal, falseVal) = if cond then trueVal else falseVal;

the ternary operator comes from functional paradigm. To prove this makes a example in smlnj :

fun ternary(cond, trueVal, falseVal) = if cond then trueVal else falseVal;

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文