三元操作符在这段代码中是如何工作的?

huangapple go评论88阅读模式
英文:

How does the Ternary Operator work in this piece of code?

问题

我有一小段设置颜色的函数代码,看起来像这样:

  1. private Color color = Color.CYAN;
  2. public void setColor(Color c) {
  3. color = c != null ? c : color;
  4. repaint();
  5. }

这是不是意味着类似于这样?

  1. color = c;
  2. if (c != null) {
  3. color = c;
  4. } else {
  5. c = color;
  6. }

我真的无法理解这段代码。请给我一些启示。

英文:

I have a small piece of code of a function to set color that looks like this:

  1. private Color color = Color.CYAN;
  2. public void setColor(Color c) {
  3. color = c != null ?c :color;
  4. repaint();
  5. }

Does it means something like this?

  1. color = c;
  2. if (c != null) {
  3. color = c;
  4. } else {
  5. c = color;
  6. }

I can't really wrap my head around this piece of code. Please enlighten me.

答案1

得分: 2

这更像是

  1. if (c != null) {
  2. color = c;
  3. } else {
  4. color = color;
  5. }

而这实际上因为 color = color; 本质上没有任何作用,所以等同于:

  1. if (c != null) {
  2. color = c;
  3. }
英文:

It's more like

  1. if (c != null) {
  2. color = c;
  3. } else {
  4. color = color;
  5. }

which, in turn, because color = color; essentially does nothing, is the same as:

  1. if (c != null) {
  2. color = c;
  3. }

huangapple
  • 本文由 发表于 2020年9月28日 12:37:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/64096020.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定