如何调用字典中存储的动作? [英] How to call an action stored in Dictionary?

查看:334
本文介绍了如何调用字典中存储的动作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试设置一个字典,然后将其存储为 listbox 中的项目

I am attempting to setup a dictionary that will then have its keys stored as items in a listbox.

我已经能够建立一个字典,然后有输入列表框,但我不知道如何执行与键相关联的操作。从上一个线程中,有一个建议,但我遇到了问题:原始主题

I have been able to establish a dictionary that then has its keys entered in the listbox, but I'm not sure how to then execute the action associated with the key. From the previous thread there was a recommendation, but I've ran into issues with it: Original Thread

Dictionary<string, Action> dict = new Dictionary<string, Action>();
public void SetDictionary()
    {
       //add entries to the dictionary
        dict["cat"] = new Action(Cat);
        dict["dog"] = new Action(Dog);

        //add each dictionary entry to the listbox.
        foreach (string key in dict.Keys)
        {
            listboxTest.Items.Add(key);
        }                            
    }

     //when an item in the listbox is double clicked
     private void listboxTest_DoubleClick(object sender, EventArgs e)
     {
         testrun(listboxCases.SelectedItem.ToString());             
     }

     public void testrun(string n)
     {
         //this is supposed to receive the item that was double clicked in the listbox, and run it's corresponding action as defined in the dictionary.
         var action = dict[n] as Action action();
     }

我相信我上面的代码大都是正确的,我理解它,但是action action();行动行:

I believe that my code above is mostly correct and that I'm understanding it, however the action line:

var action = dict[n] as Action action();

显示一条错误,指出'action'是期待一个';'。我的逻辑在这里准确吗?如果是这样,为什么动作调用不正确?

Shows an error stating 'action' is expecting a ';'. Is my logic here accurate? If so, why is the action call incorrect?

推荐答案

你缺少一个;

var action = dict[n] as Action; action();
                              ↑

这篇关于如何调用字典中存储的动作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆