我正在读这个博客:https://deniskyashif.com/2019/11/20/a-practical-guide-to-state-machines/
这里有一段代码:
State ChangeState(State current, Input input) =>
(current, input) switch
{
(State.Created, Input.Admit) => State.Ready,
(State.Ready, Input.ScheduleDispatch) => State.Running,
(State.Running, Input.IOorEventWait) => State.Waiting,
(State.Waiting, Input.IOorEventComplete) => State.Ready,
(State.Running, Input.Interrupt) => State.Ready,
(State.Running, Input.Exit) => State.Terminated,
_ => throw new NotSupportedException(
$"{current} has no transition on {input}")
};我在中测试过的效果很好。
然而,我不知道为什么它的工作和如何。我甚至不知道应该是什么。
我得到的State ChangeState(State current, Input input) =>部分是一个方法签名和一个表达式体,我认为(current, input) switch是某种匿名方法签名,但是它到底是什么,如果我将它粘贴到一个常规方法中,它为什么不能工作呢?
发布于 2020-05-06 22:44:54
在您的示例中,这个新的C# 8开关表达式基本上匹配元组中的模式。(current, input) switch告诉您,您将比较这两个值。(State.XYZ, Input.ABC)告诉您,您将检查是否current == State.XYZ && input == Input.ABC,如果是,返回表达式后的=>运算符,否则检查下一个。_匹配任何值,可以用作(_, X)或仅用作_。
https://stackoverflow.com/questions/61645638
复制相似问题