如何调用字典中存储的操作

本文关键字:存储 操作 字典 何调用 调用 | 更新日期: 2023-09-27 17:51:12

我正在尝试设置一个dictionary,然后将其keys存储为items中的listbox

我已经能够建立一个dictionary,然后在listbox中输入其keys,但我不确定如何执行与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();
     }

我相信我上面的代码大部分是正确的,我理解它,但是操作行:

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

显示一个错误,说明'action'正在等待';'。我的逻辑准确吗?如果是,为什么动作调用不正确?

如何调用字典中存储的操作

你缺少一个;:

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

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

Dictionary<string, Action> dict;

如果不匹配,请指出定义是什么

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

dict[key]();

dict[key].Invoke();

要将其存储为变量,则根本不需要强制类型转换:

Action action = dict[key];

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

Action action = dict[key] as Action;

然后你可以像上面那样调用它:

action();

action.Invoke();

你的测试应该是

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

假设您的字典是Dictionary<string, Action>,如@Servy建议的