如何存储从switch语句的案件清单? [英] How to store a list of Cases from Switch Statement?
问题描述
在我的节目,我有,当用户双击一个对象,它看起来switch语句来看看应该发生什么事件列表框。由于名单开始变得越来越大我很好奇,如果在switch语句中有以避免维持2个地方(一次在列表中的对象列表添加到列表框的方式,一旦。
有没有一种方法来索引/读取/存储我的switch语句的各种情况,然后将其作为对象添加到我的列表框?
In my program I have a listbox that when the user double clicks an object it looks to a switch statement to see what event should occur. As the list begins getting larger I'm curious if there is a way to avoid having to maintain the list of objects in 2 places (once in a list to Add to the listbox, and once in the switch statement. Is there a way to index/read/store the various Cases of my switch statement, then add them as objects to my listbox?
例如:(不工作,只是一个理论)
Example: (doesn't work, just a theory)
Switch (n)
ForEach (Case c in Cases)
{
arrayCases.Add(c);
}
listbox.Items.AddRange(arrayCases);
编辑:
去的字典建议我现在有:
Going on the Dictionary recommendations I now have:
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();
}
我相信我的code以上大多是正确的,而且我理解它,然而行动路线:
VAR行动=字典[n],如行动对行动();
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?
推荐答案
词典<字符串,作用>
是要避免的方式。 Dictionary.Keys
变成 ListBox.Items
。
Dictionary<string, Action>
is the way to avoid. Dictionary.Keys
becomes ListBox.Items
.
开关(N)
变为
var action = dict[n] as Action
action();
这篇关于如何存储从switch语句的案件清单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!