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

Fuz*_*ans -4 c# dictionary action listbox winforms

我试图设置一个dictionary将其keys存储为itemsa listbox.

我已经能够建立一个dictionary然后keys输入它listbox,但我不知道如何然后执行与之相关的动作key.从上一个帖子中有一个建议,但我遇到了问题:原始线程

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();
     }
Run Code Online (Sandbox Code Playgroud)

我相信我上面的代码大多是正确的,我理解它,但行动方面:

var action = dict[n] as Action action();
Run Code Online (Sandbox Code Playgroud)

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

dtb*_*dtb 10

你错过了一个;:

var action = dict[n] as Action; action();
                              ?
Run Code Online (Sandbox Code Playgroud)


Ser*_*rvy 7

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

Dictionary<string, Action> dict;
Run Code Online (Sandbox Code Playgroud)

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

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

dict[key]();
Run Code Online (Sandbox Code Playgroud)

要么

dict[key].Invoke();
Run Code Online (Sandbox Code Playgroud)

要将它存储为变量,您(不应该)需要一个演员:

Action action = dict[key];
Run Code Online (Sandbox Code Playgroud)

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

Action action = dict[key] as Action;
Run Code Online (Sandbox Code Playgroud)

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

action();
Run Code Online (Sandbox Code Playgroud)

要么

action.Invoke();
Run Code Online (Sandbox Code Playgroud)