2011-05-26 54 views
6

我试图填充一个Libgee HashMap,其中每个条目都有一个字符串作为关键字,并将一个函数作为值。这可能吗?我想这样的事情:Gee 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); 
} 

但也许这是不是最好的方法是什么?

回答

5

代表是你要找的。但我最后一次检查,泛型不支持的代表,所以不那么优雅的方式是把它包起来:

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

我认为泛型是实现的,或者至少在[tutorial](http://live.gnome.org/Vala/Tutorial#Generics) – Riazm 2011-05-28 20:20:41

+0

中有与它们相关的部分我的意思是'使用委托作为泛型参数'不支持,而不是一般的泛型:)编辑。 – takoi 2011-05-28 21:58:18

2

只用[CCODE(has_target = FALSE)]的代表是可能的,否则你必须按照takoi的建议创建一个包装。