How to call an action stored in Dictionary? [closed]

不羁岁月 提交于 2019-12-25 20:02:45

问题


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

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

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


回答1:


You're missing a ;:

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



回答2:


First off, I'm assuming the definition of the dictionary, since it wasn't listed is the following:

Dictionary<string, Action> dict;

Please indicate what the definition is if that doesn't match.

To execute the action for a given key all you need is:

dict[key]();

or

dict[key].Invoke();

To store it as a variable you (shouldn't) need a cast at all:

Action action = dict[key];

If you do need to cast it (meaning your dictionary definition differs from what I listed), you can do so like this:

Action action = dict[key] as Action;

You can then invoke it as shown above:

action();

or

action.Invoke();



回答3:


Your testrun should be

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]();
}

Based on the assumption your dictionary is Dictionary<string, Action> as @Servy suggested



来源:https://stackoverflow.com/questions/14264317/how-to-call-an-action-stored-in-dictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!