我在oracles网站上看到的这段代码有问题。有人能为我解释一下吗?
Action updateCursorAction = new AbstractAction() {
boolean shouldDraw = false;
public void actionPerformed(ActionEvent e) {
if (shouldDraw = !shouldDraw) { // <----- here is my problem, what's this condition for?
// isn't it always false?
drawCursor();
} else {
eraseCursor();
}
}
};
new Timer(300, updateCursorAction).start();
if (shouldDraw = !shouldDraw)
这不是在做if(shouldDraw != shoundDraw)
。我想这就是让你困惑的地方。相反,它对shouldDraw
进行否定,并检查结果。
因此,功能是,如果shouldDraw
曾经是false
进入该条件,它将被设置为true
,并且if
块将执行。如果shouldDraw
进入条件为true,则它将被否定,而else块将被执行。
这将实质上在每次执行ActionListener
时在true
和false
之间切换shouldDraw
,这将使光标闪烁。
if (shouldDraw = !shouldDraw)
可以重写为
shouldDraw = !shouldDraw;
if (shouldDraw)
这是一个C风格的技巧,条件检查中的赋值可以产生更优雅的代码,但它可能会让新程序员
这实际上不是一个多余的条件,它只是"棘手"、"密集"、难以阅读的代码!
棘手的是shouldDraw = !shouldDraw
就是我所说的"触发器分配"。每次迭代都会将相反的内容分配给它的前一个,并执行替换。
太难看了!摸索一下,很高兴这不是你的代码;-)
干杯。基思。
基本上,这段代码将抽取2次中的1次。并且它将擦除另一个50%的
有点令人困惑,但合乎逻辑。