关闭:为什么他们这么有用? [英] Closures: why are they so useful?

查看:81
本文介绍了关闭:为什么他们这么有用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为 OO 开发人员,也许我很难看到它的价值。他们有什么附加价值?

As an OO developer, maybe I have difficulty seeing its value. What added value do they give? Do they fit in an OO world?

推荐答案

关闭不会给你任何额外的力量。

Closures don't give you any extra power.

任何你可以实现的,你可以实现没有他们。

Anything you can achieve with them you can achieve without them.

但他们非常有用,使代码更清晰和可读。
因为我们都知道干净可读的短代码是一个更容易调试和包含更少的错误的代码。

But they are very usable for making code more clear and readable. And as we all know clean readable short code is a code that is easier to debug and contains fewer bugs.

让我给你简短的Java示例用法:

Let me give you short Java example of possible usage:

    button.addActionListener(new ActionListener() {
        @Override public void actionPerformed(ActionEvent e) {
            System.out.println("Pressed");
        }
    });

将被替换(如果Java有闭包):

Would be replaced (if Java had closures) with:

button.addActionListener( { System.out.println("Pressed"); } );

这篇关于关闭:为什么他们这么有用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆