你真的可以用一些更具功能性的编程风格的代码来充实你的程序。我假设您想做一些更复杂的事情,而不仅仅是退出,因此我提出了一种模式,对于更基本的场景来说,这将是矫枉过正的。这里的要点是您应该能够用更少的代码指定所有操作,几乎都在一个地方。运行的方法应该是描述性的——几乎是自我记录的。
// Define a class that can return some basic information about what should happen next
// This only has one property but could be much richer
public class KeyActionResult {
public KeyActionResult(bool shouldQuit) {
ShouldQuit = false;
}
public bool ShouldQuit { get; }
// put other return values or information
}
public static class MyProgram {
// Doing this in advance requires the class to be immutable
private static KeyActionResult _shouldNotQuit = new KeyActionResult(false);
private static KeyActionResult _shouldQuit = new KeyActionResult(true);
// Work up the vocabulary that you want to be able to use
private static Action<KeyActionResult> KeepLoopingAfter(Action action) =>
() => {
action();
return _shouldNotQuit;
};
private static Action<KeyActionResult> QuitAfter(Action action) =>
() => {
action();
return _shouldQuit;
};
private Action<KeyActionResult> Quit() => () => _shouldQuit;
private void DoSomethingComplicated() { /* whatever */ }
有了这些,您就可以使用它们来真正清理您的代码。
// Bind keys to vocabulary and actions, all in high-signal code
private static keyActions = new Dictionary<char, Action<KeyActionResult>> {
['p'] = KeepLoopingAfter(() => Console.WriteLine("You pressed 'p'!")),
['d'] = KeepLoopingAfter(DoSomethingComplicated),
['q'] = Quit(),
['x'] = QuitAfter(() => Console.WriteLine("Delete, then quit!"))
}
.AsReadOnly();
// Run the main decision loop
public static void Main() {
bool shouldQuit;
do {
ConsoleKeyInfo keyInfo = Console.ReadKey(true);
Action action;
if (keyActions.TryGetValue(keyInfo.KeyChar, out action)) {
shouldQuit = action().ShouldQuit;
} else {
shouldQuit = false;
}
} while (!shouldQuit)
}
}
你可以开始做一些多播来把它提升到一个新的水平......