【问题标题】:Gee HashMap containing methods as valuesGee HashMap 包含方法作为值
【发布时间】:2011-09-02 23:45:46
【问题描述】:

我正在尝试填充一个 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);
}

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

【问题讨论】:

    标签: vala genie libgee


    【解决方案1】:

    代表是您正在寻找的。但是上次我检查时,泛型不支持委托,所以一个不太优雅的方法是包装它:

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

    【讨论】:

    • 我认为泛型已经实现,或者至少在tutorial中有一个与它们相关的部分
    • 我的意思是不支持“使用委托作为泛型类型参数”,一般不支持泛型:) 已编辑。
    【解决方案2】:

    这只能用于具有 [CCode (has_target = false)] 的委托,否则您必须按照 takoi 的建议创建一个包装器。

    【讨论】:

      猜你喜欢
      • 2015-10-31
      • 2016-02-08
      • 2014-10-13
      • 2012-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多