vala - 如何在闭包中捕获 int 值?
问题描述
我有一个应用程序,其中包含任意数量的元素,这些元素都调用一个需要在创建时定义的参数的函数。这是一个简化的示例,但在这里我希望制作 3 个打印 0、1、2 的按钮,但只制作 3 个打印 3 的按钮。
var application_window = new Gtk.ApplicationWindow (this);
var grid = new Gtk.Grid ();
for (int i = 0; i < 3; i++) {
var button = new Gtk.Button() {expand=true};
button.clicked.connect (() => {
print(i.to_string());
});
grid.add(button);
}
application_window.add(grid);
application_window.show_all ();
如何将我的应用更改为打印 123?
解决方案
这是我的基本代码:
public class MyApplication : Gtk.Application {
public MyApplication () {
Object(application_id: "testing.my.application",
flags : ApplicationFlags.FLAGS_NONE);
}
protected override void activate () {
var application_window = new Gtk.ApplicationWindow (this);
var grid = new Gtk.Grid ();
for (int i = 0; i < 3; i++) {
var button = new Gtk.Button() {expand=true};
button.clicked.connect (() => {
print(i.to_string());
});
grid.add(button);
}
application_window.add(grid);
application_window.show_all ();
}
public static int main (string[] args) {
MyApplication app = new MyApplication ();
return app.run (args);
}
}
如果你这样执行它,你会得到333
标准输出。
问题出在捕获代码中:
for (int i = 0; i < 3; i++) {
var button = new Gtk.Button() {expand=true};
button.clicked.connect (() => {
print(i.to_string());
});
闭包按位置捕获变量 i。这意味着当您在创建闭包后更改 i 变量时,更改也将在闭包中可见。
其他编程语言(例如 C++)有明确的捕获列表来避免这个问题。
一个快速而肮脏的解决方案是在循环范围内使用局部变量:
for (int i = 0; i < 3; i++) {
var captured_i = i;
var button = new Gtk.Button() {expand=true};
button.clicked.connect (() => {
print(captured_i.to_string());
});
这打印:012
如预期的那样。
更好的解决方案是使用将闭包作为委托返回的函数。我刚刚尝试过,但由于某种原因它不起作用:
public class MyApplication : Gtk.Application {
public MyApplication () {
Object(application_id: "testing.my.application",
flags : ApplicationFlags.FLAGS_NONE);
}
delegate void ButtonClick();
private ButtonClick make_print_event (int i) {
return () => print (i.to_string());
}
protected override void activate () {
var application_window = new Gtk.ApplicationWindow (this);
var grid = new Gtk.Grid ();
for (int i = 0; i < 3; i++) {
var button = new Gtk.Button() { expand=true };
var print_event = make_print_event (i);
button.clicked.connect (print_event);
grid.add(button);
}
application_window.add (grid);
application_window.show_all ();
}
public static int main (string[] args) {
MyApplication app = new MyApplication ();
return app.run (args);
}
}
编译器 (valac-0.52) 警告:
three_buttons.vala:20.37-20.47: warning: copying delegates is not supported
three_buttons.vala:20.37-20.47: warning: Connecting delegates to signals is experimental
button.clicked.connect (print_event);
^^^^^^^^^^^
推荐阅读
- python - 流式传输文件时如何限制内存开销?
- excel - 错误处理:如果出现运行时错误“1004”,则跳过自动填充公式
- c++ - C++ 我应该使用转发引用吗?
- javascript - 如何强制 Google Docs 从 Chrome 扩展中呈现 HTML 而不是 Canvas?
- swift - Swift - 自定义和默认 TableView 标题的混合
- javascript - React Native 无法调用 BackgroundGeolocation.start
- javascript - 如何防止用户直接访问我的html网站?
- python - 为什么当它适用于其他数组时,我会得到“RuntimeError:列需要是 1D(图像不是)”?
- linux - 是否可以配置 crontab 在夏令时生效时调整其时间?
- python - 查找和替换 Pandas 仅索引每一行