Gee HashMap containing methods as values

隐身守侯 提交于 2019-12-07 03:22:48

问题


I'm trying to fill a Libgee HashMap where each entry has a string as key, and a function as value. Is this possible? I want this sort of thing:

var keybindings = new Gee.HashMap<string, function> ();
keybindings.set ("<control>h", this.show_help ());
keybindings.set ("<control>q", this.explode ());

so that I can eventually do something like this:

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);
}

But perhaps this isn't the best way?


回答1:


Delegates are what you're looking for. But last time I checked, generics didn't support delegates, so a not-so-elegant way is to wrap it:

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);



回答2:


It is possible only for delegates with [CCode (has_target = false)], otherwise you have to create a wrapper as takoi suggested.



来源:https://stackoverflow.com/questions/6145635/gee-hashmap-containing-methods-as-values

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!