如何调用存储在Dictionary中的动作?

时间:2013-01-10 18:01:21

标签: c# winforms dictionary listbox action

我正在尝试设置dictionary,然后keysitems存储为listbox dictionary

我已经能够建立一个keys,然后在listbox中输入key,但我不确定如何执行与{{{}}相关联的操作1}}。从上一个帖子中有一个建议,但我遇到了问题: 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();
     }

我相信我上面的代码大部分是正确的,而且我理解它,不过行动方面:

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

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

3 个答案:

答案 0 :(得分:10)

您错过了;

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

答案 1 :(得分:7)

首先,我假设字典的定义,因为它没有列出如下:

Dictionary<string, Action> dict;

如果不匹配,请说明定义是什么。

要执行给定键的操作,您只需:

dict[key]();

dict[key].Invoke();

要将其存储为变量,您(不应该)根本不需要演员:

Action action = dict[key];

如果你确实需要施放它(意味着你的字典定义与我列出的不同),你可以这样做:

Action action = dict[key] as Action;

然后您可以调用它,如上所示:

action();

action.Invoke();

答案 2 :(得分:1)

你的测试应该是

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.
     dict[n]();
}

基于假设您的词典{@ 1}}为@Servy建议