访问存储在Action[]字典中的多个方法
本文关键字:方法 字典 存储 Action 访问 | 更新日期: 2023-09-27 18:18:28
这个问题涉及字典中操作的使用。我想做类似的事情,但是使用每个操作有多个方法:
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[]中包含的方法?
你就快成功了。你已经有了一个动作数组,所以现在你需要做的就是按顺序执行这些动作。
c#中的 Action
s和Func
s就像任何其他对象一样-您可以将它们放入数组,将它们赋值给变量,将它们作为参数传递给方法,等等。唯一的区别是您可以调用一个操作。它的语法类似于调用方法的语法:
Action myAction = ...
myAction(); // call the action
因此,要执行数组中的动作,您可以通过foreach
将数组逐个取出,并在循环体中调用每个动作。
private static void morseThis(string message)
{
char[] messageComponents = message.ToCharArray();
if (morseDictionary.ContainsKey(messageComponents[i]))
{
Action[] currentMorseArray = morseDictionary[messageComponents[i]];
foreach (Action action in currentMorseArray)
{
action();
}
}
}
列举操作并执行。
private static void morseThis(string message)
{
char[] messageComponents = message.ToCharArray();
foreach(char c in messageComponents)
{
Action[] actions;
if (morseDictionary.TryGetValue(c, out actions))
{
foreach(Action action in actions)
{
action();
}
}
}
}
使用foreach
遍历动作数组:
private static void morseThis(string message){
char[] messageComponents = message.ToCharArray();
Action[] currentMorseArray;
if (morseDictionary.TryGetValue(messageComponents[i], out currentMorseArray))
{
foreach(var action in currentMorseArray)
{
action();
}
}
}
我不确定你期望从Console.WriteLine
,但是你观察到的行为是预期的,因为WriteLine
调用ToString
对对象进行打印,对于数组(和其他类型的ToString
没有被覆盖),它只是返回类型名称。
static readonly Dictionary<char, List<Action>> morseDictionary = new Dictionary<char,List<Action>>
{
{ 'a', new List<Action> {dot, dash} },
{ 'b', new List<Action> {dash, dot, dot, dot} },
{ 'c', new List<Action> {dash, dot, dash, dot} },
{ 'd', new List<Action> {dash, dot, dot} },
{ 'e', new List<Action> {dot} }
// etc
};
private static void morseThis(string messageSrc)
{
foreach(char message in messageSrc.ToCharArray())
{
List<Action> currentMorseArray;
if (morseDictionary.TryGetValue(message, out currentMorseArray))
{
currentMorseArray.ForEach(x=>x());
}
}
}