【问题标题】:How to call an action stored in Dictionary? [closed]如何调用存储在字典中的动作? [关闭]
【发布时间】:2013-01-10 18:01:20
【问题描述】:

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

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

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

【问题讨论】:

  • 再次查看此答案stackoverflow.com/a/14244589/1906557 并阅读第一条评论。
  • Fuzz,您的示例代码缺少最重要的部分 - 您使用的字典类型(我怀疑是非通用字典)。请检查原始答案中建议的确切类型。
  • @L4V - 我去重读了,没有看到你可能提到的任何新内容。
  • @Alexei - 我添加了字典类型。我为遗漏道歉。

标签: c# winforms dictionary listbox action


【解决方案1】:

您缺少;

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

【讨论】:

    【解决方案2】:

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

    Dictionary<string, Action> dict;
    

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

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

    dict[key]();
    

    dict[key].Invoke();
    

    要将其存储为一个变量,您(不应该)根本不需要强制转换:

    Action action = dict[key];
    

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

    Action action = dict[key] as Action;
    

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

    action();
    

    action.Invoke();
    

    【讨论】:

    • 不需要作为操作符,直接调用Action dict[key]();
    • @NasmiSabeer 你看了我的回答了吗?我一开始就这么说。当我到达as 运算符时,我特别指出,只有Dictionary 的签名不匹配时才合适,即如果它是恰好包含Action 对象作为值的Dictionary&lt;string, object&gt;
    • 对不起,我的错误没有完整阅读答案
    【解决方案3】:

    你的测试应该是

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

    根据@Servy 建议的假设您的字典是Dictionary&lt;string, Action&gt;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多