【问题标题】:Ternary operator confusion in C#C#中的三元运算符混淆
【发布时间】:2021-12-30 03:51:59
【问题描述】:

谁能解释一下这行 C# 代码是如何计算的?

int myInt = false? true ? 0 : 1 : 2; // ans = 2

【问题讨论】:

  • 天哪,我的眼睛....这段代码应该重写(句号)
  • 为该行添加括号以使其更可靠:int myInt = false ? (true ? 0 : 1) : 2; 并且很容易找到原因
  • 我的建议: 1. 学习manual。 2.用变量替换你的真假,玩弄它们的值,并尝试自己弄清楚。 3.take the tour,阅读how to ask a good question和阅读what's on topic

标签: c# visual-studio-2022


【解决方案1】:

让我们添加 圆括号 让行更可读

int myInt = false ? (true ? 0 : 1) : 2;

现在让我们计算这些值。对于 inner ?: 我们有

(true ? 0 : 1)

等于 0。那么外部?:会是

int myInt = false ? 0 : 2;

等于2

【讨论】:

  • 还可以补充一点,false 的计算结果始终为 false,因此表达式中唯一有意义的部分是 2,因此可以缩短为 int myInt = 2;
猜你喜欢
  • 2014-02-08
  • 2012-02-13
  • 2020-10-25
  • 2012-03-09
  • 1970-01-01
  • 2012-12-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多