我正在尝试用Gtk3了解Vala代表。 我测试了回调和lambda没有问题。 我想测试一个委托回调,这里是我的代码:
using Gtk;
delegate void typeDelegate(Button button);
int main (string[] args) {
Gtk.init (ref args);
typeDelegate cb = cbLabelf;
var window = new Window ();
window.title = "First GTK+ Program";
window.border_width = 10;
window.window_position = WindowPosition.CENTER;
window.set_default_size (350, 70);
window.destroy.connect (Gtk.main_quit);
var button = new Button.with_label ("Click me!");
//button.clicked.connect (cb);
//button.clicked+= cb;
button.clicked.connect+=cb;
window.add (button);
window.show_all ();
Gtk.main ();
return 0;
}
void cbLabelf(Button button)
{
button.label = "tank yu";
}
我还用红色生成的C代码(当我使用lambda时)来理解。
这里的编译错误:
GTKsampleDelegate.vala:20.5-20.30:错误:类型Gtk.Button.clicked.connect' and
typeDelegate'不支持算术运算
button.clicked.connect + = CB;
答案 0 :(得分:1)
好吧,
似乎你想获得保存发出信号的实例的内部变量,我发现vala不允许你使用委托变量来通过参数获取它,但是,你可以使用其中一个表单下面:使用无委托变量(A)或使用闭包(B)绕过错误。
public class FooSignalClass : Object {
/* Gtk Button.clicked signal has the void f(void) signature */
public signal void on_foo ();
public void foo() {
on_foo();
}
}
public delegate void FooSignalFunc (FooSignalClass fooer);
void on_foo_handler (FooSignalClass fooer) {
long fooer_memory_address = (long)fooer;
GLib.message(@"fooer exists? $(fooer!=null).");
GLib.message(@"address=$fooer_memory_address.");
}
int main () {
var foo_signal = new FooSignalClass();
long fooer_memory_address = (long)foo_signal;
GLib.message(@"foo_signal address=$fooer_memory_address.");
/* Option A: Connect directly without the delegate variable */
foo_signal.on_foo.connect(on_foo_handler);
/* Option B: You cant use a delegate directly, bypass it with a closure */
FooSignalFunc func = on_foo_handler;
foo_signal.on_foo.connect((instance) => {
func(instance);
});
foo_signal.foo();
return 0;
}