を書くことができます。最も簡単な解決策は、キーとコマンドテキストの間に直接マッピングすることです。列挙型の値を入力キーから、コマンドテキストに列挙値から -
Dictionary<ConsoleKey, String> map = new Dictionary<ConsoleKey, String>()
{
{ ConsoleKey.A, "process image" },
{ ConsoleKey.B, "apply blur effect" },
{ ConsoleKey.C, "save as png" }
};
ConsoleKey key = Console.ReadKey().Key;
String command;
if (map.TryGetValue(key, out command))
{
SendCommand(command);
}
else
{
HandleInvalidInput();
}
は、実際のニーズに応じて、2段階のマッピングを実行するためのクリーナー解決策かもしれません。また、コマンドクラスの作成とコマンド用の静的インスタンスの提供について考える必要があります。
public class Command
{
public Command(String commandText)
{
this.CommandText = commandText;
}
public String CommandText { get; private set; }
public void Send()
{
// Dummy implementation.
Console.WriteLine(this.CommandText);
}
// Static command instances.
public static readonly Command ProcessImage = new Command("process image");
public static readonly Command BlurImage = new Command("apply blur effect");
public static readonly Command SaveImagePng = new Command("save as png");
}
このクラスでは、コマンドを送信するコードは次のようになります。
Dictionary<ConsoleKey, Command> map = new Dictionary<ConsoleKey, Command>()
{
{ ConsoleKey.A, Command.ProcessImage },
{ ConsoleKey.B, Command.BlurImage},
{ ConsoleKey.C, Command.SaveImagePng }
};
ConsoleKey key = Console.ReadKey().Key;
Command command;
if (map.TryGetValue(key, out command))
{
command.Send();
}
else
{
HandleInvalidInput();
}
非常に良い答えです。 –