2011-05-26 84 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的建議創建一個包裝。