英文:
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;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论