我正在尝试填充一个Libgee HashMap,其中每个条目都有一个字符串作为键,一个函数作为值。这可能吗?我想要这种东西:
var keybindings = new Gee.HashMap<string, function> ();
keybindings.set ("<control>h", this.show_help ());
keybindings.set ("<control>q", this.explode ());
这样我最终可以做这样的事情:
foreach (var entry in keybindings.entries) {
uint key_code;
Gdk.ModifierType accelerator_mods;
Gtk.accelerator_parse((string) entry.key, out key_code, out accelerator_mods);
accel_group.connect(key_code, accelerator_mods, Gtk.AccelFlags.VISIBLE, entry.value);
}
但也许这不是最好的方式?
您正在寻找代理。但上次我检查时,泛型不支持委托,所以一种不太优雅的方法是包装它:
delegate void DelegateType();
private class DelegateWrapper {
public DelegateType d;
public DelegateWrapper(DelegateType d) {
this.d = d;
}
}
Gee.HashMap keybindings = new Gee.HashMap<string, DelegateWrapper> ();
keybindings.set ("<control>h", new DelegateWrapper(this.show_help));
keybindings.set ("<control>q", new DelegateWrapper(this.explode));
//then connect like you normally would do:
accel_group.connect(entry.value.d);
这只适用于具有[CCode(has_target=false)]的委托,否则您必须按照takoi的建议创建包装器。