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

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

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

问题

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

private Color color = Color.CYAN;

public void setColor(Color c) {
    color = c != null ? c : color;
    repaint();
}

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

color = c;
if (c != null) {
    color = c;
} else {
    c = color;
}

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

英文:

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

private Color color = Color.CYAN;

public void setColor(Color c) {
		color = c != null ?c :color;
		repaint();
	}

Does it means something like this?

color = c;
if (c != null) {
        color = c;
        } else {
        c = color;
}

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

答案1

得分: 2

这更像是

if (c != null) {
    color = c;
} else {
    color = color;
}

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

if (c != null) {
    color = c;
}
英文:

It's more like

if (c != null) {
    color = c;
} else {
    color = color;
}

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

if (c != null) {
    color = c;
}

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:

确定