【发布时间】:2013-01-10 18:01:20
【问题描述】:
我正在尝试设置一个dictionary,然后将其keys 存储为items 在listbox 中。
我已经能够建立一个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