【发布时间】:2016-01-19 09:40:40
【问题描述】:
This question covers the use of actions in a dictionary. 我想做类似的事情,但每次操作不止一种方法:
static readonly Dictionary<char, Action[]> morseDictionary = new Dictionary<char,Action[]>
{
{ 'a', new Action[] {dot, dash} },
{ 'b', new Action[] {dash, dot, dot, dot} },
{ 'c', new Action[] {dash, dot, dash, dot} },
{ 'd', new Action[] {dash, dot, dot} },
{ 'e', new Action[] {dot} }
// etc
};
dot 和 dash 指的是这些私有函数:
private static void dash(){
Console.Beep(300, timeUnit*3);
}
private static void dot(){
Console.Beep(300, timeUnit);
}
我还有另一个函数morseThis,它旨在将消息字符串转换为音频输出:
private static void morseThis(string message){
char[] messageComponents = message.ToCharArray();
if (morseDictionary.ContainsKey(messageComponents[i])){
Action[] currentMorseArray = morseDictionary[messageComponents[i]];
Console.WriteLine(currentMorseArray); // prints "System.Action[]"
}
}
在上面的示例中,我可以为输入消息中包含的每个字母将“System.Action[]”打印到控制台。但是,我的意图是按顺序调用currentMorseArray 中的方法。
如何访问字典中给定 Action[] 中包含的方法?
【问题讨论】:
-
对于您的具体情况,我只会将 lamda 存储为(单个)动作。所以
... { 'a', () => { dot(); dash(); }, ...。这使调用保持简单,并且并没有真正改变字典设置。您也可以考虑将字段的类型设为 IReadOnlyDictionary,因为我认为它的内容不会被更改。
标签: c# dictionary console-application morse-code