在Vala中,有一种方法可以让多个信号处理程序在访问本地范围的同时执行相同的代码?
使用委托定义lambda是可行的,但需要委托定义,并发出警告“不支持复制委托”:
delegate void ChangeHandler ();
void test () {
var answer = 42;
ChangeHandler handler = () => {
debug("size or position changed. answer: %i", answer);
};
size_changed.connect (handler);
position_changed.connect (handler);
}
据我所知,还有没有办法将信息传递给处理程序?像这样:
void test () {
var answer = 42;
size_changed.connect (handler, answer);
position_changed.connect (handler, answer);
}
void handler (answer) {
debug("size or position changed. answer: %i", answer);
}
我可以这样做,但这需要很多额外的代码,尤其是当有很多参数时。
void test () {
var answer = 42;
size_changed.connect (handler, answer);
position_changed.connect (() => handler(answer));
}
void handler (answer) {
debug("size or position changed. answer: %i", answer);
}
是否可以将多个信号连接到一个匿名函数?像这样:
void test () {
var answer = 42;
multi_connect(size_changed, position_changed, () => {
debug("size or position changed. answer: %i", answer);
});
}
答案 0 :(得分:2)
如何使用this
传递数据:
public class Test : GLib.Object {
public signal void sig_1 ();
public signal void sig_2 ();
private int answer = 42;
private void sig_handler (Test t) {
stdout.printf("sig_1 or sig_2 triggered. answer: %d\n", answer);
}
public static int main(string[] args) {
Test t1 = new Test();
t1.sig_1.connect(t1.sig_handler);
t1.sig_2.connect(t1.sig_handler);
t1.sig_1();
t1.sig_2();
return 0;
}
}
也许通过两个类更容易阅读:
public class SignalRaiser : GLib.Object {
public signal void sig_1 ();
public signal void sig_2 ();
}
public class SignalReceiver : GLib.Object {
private int answer = 42;
public void sig_handler (SignalRaiser sender) {
stdout.printf("sig_1 or sig_2 triggered. answer: %d\n", answer);
}
}
int main(string[] args) {
var raiser = new SignalRaiser();
var receiver = new SignalReceiver();
raiser.sig_1.connect(receiver.sig_handler);
raiser.sig_2.connect(receiver.sig_handler);
raiser.sig_1();
raiser.sig_2();
return 0;
}