-4

我正在尝试设置一个dictionary,然后将其keys存储itemslistbox.

我已经能够建立一个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();
     }

我相信我上面的代码大部分是正确的并且我理解它,但是行动路线:

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

显示一个错误,指出“操作”需要一个';'. 我这里的逻辑准确吗?如果是这样,为什么动作调用不正确?

4

3 回答 3

10

你错过了一个;

var action = dict[n] as Action; action();
                              ↑
于 2013-01-10T18:03:48.773 回答
7

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

Dictionary<string, Action> dict;

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

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

dict[key]();

或者

dict[key].Invoke();

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

Action action = dict[key];

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

Action action = dict[key] as Action;

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

action();

或者

action.Invoke();
于 2013-01-10T18:04:29.530 回答
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]();
}

基于假设您的字典Dictionary<string, Action>与@Servy 建议的一样

于 2013-01-10T18:10:27.690 回答