冗余条件



我在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时在truefalse之间切换shouldDraw,这将使光标闪烁。

if (shouldDraw = !shouldDraw)

可以重写为

shouldDraw = !shouldDraw;
if (shouldDraw)

这是一个C风格的技巧,条件检查中的赋值可以产生更优雅的代码,但它可能会让新程序员

感到困惑

这实际上不是一个多余的条件,它只是"棘手"、"密集"、难以阅读的代码!

棘手的是shouldDraw = !shouldDraw就是我所说的"触发器分配"。每次迭代都会将相反的内容分配给它的前一个,并执行替换。

太难看了!摸索一下,很高兴这不是你的代码;-)

干杯。基思。

基本上,这段代码将抽取2次中的1次。并且它将擦除另一个50%的

有点令人困惑,但合乎逻辑。

最新更新