【发布时间】:2019-03-16 19:59:45
【问题描述】:
我正在尝试实现状态机。这种情况是,如果提交了文件,则将其发送以供审核,然后获得批准。
但它会抛出一个错误,即已审核 -> 批准转换无效。
这是可能提供更好图片的代码。
为什么会抛出错误?我确保一切都井井有条,但仍然正常。
public enum ProcessState
{
Submitted,
Reviewed,
Approved
}
public enum Command
{
Submit,
Review,
Approve
}
public class Process
{
class StateTransition
{
readonly ProcessState CurrentState;
readonly Command Command;
public StateTransition(ProcessState currentState, Command command)
{
CurrentState = currentState;
Command = command;
}
public override int GetHashCode()
{
return 17 + 31 * CurrentState.GetHashCode() + 31 * Command.GetHashCode();
}
public override bool Equals(object obj)
{
StateTransition other = obj as StateTransition;
return other != null && this.CurrentState == other.CurrentState && this.Command == other.Command;
}
}
Dictionary<StateTransition, ProcessState> transitions;
public ProcessState CurrentState { get; private set; }
public Process()
{
CurrentState = ProcessState.Submitted;
transitions = new Dictionary<StateTransition, ProcessState>
{
{ new StateTransition(ProcessState.Submitted, Command.Review), ProcessState.Reviewed },
{ new StateTransition(ProcessState.Reviewed, Command.Approve), ProcessState.Approved },
};
}
public ProcessState GetNext(Command command)
{
StateTransition transition = new StateTransition(CurrentState, command);
ProcessState nextState;
if (!transitions.TryGetValue(transition, out nextState))
throw new Exception("Invalid transition: " + CurrentState + " -> " + command);
return nextState;
}
public ProcessState MoveNext(Command command)
{
CurrentState = GetNext(command);
return CurrentState;
}
}
public class Program
{
static void Main(string[] args)
{
Process p = new Process();
Console.WriteLine("Current State = " + p.CurrentState);
Console.WriteLine("Command.Submit: Current State = " + p.MoveNext(Command.Submit));
Console.WriteLine("Command.Review: Current State = " + p.MoveNext(Command.Review));
Console.WriteLine("Command.Approve: Current State = " + p.MoveNext(Command.Approve));
Console.ReadLine();
}
}
更新:
这里是错误部分:
public ProcessState GetNext(Command command)
{
StateTransition transition = new StateTransition(CurrentState, command);
ProcessState nextState;
if (!transitions.TryGetValue(transition, out nextState))
throw new Exception("Invalid transition: " + CurrentState + " -> " + command);
return nextState;
}
【问题讨论】:
-
附加调试器。步行执行和检查状态。计算机是正确的——哪些期望与持有的期望不同?请记住将问题简化为 SSCCE 问题 - 在进行此简化时会发现许多问题。
-
@user2864740:我刚刚做到了。检查谢谢
-
当然这是“错误部分”,你明确地抛出了一个异常。您是否从某个地方复制了该代码?您是否尝试过调试该代码?
-
您的
transitions字典不包含Command.Approve的单个条目。所以它当然会像预期的那样失败。 -
@CamiloTerevinto:我的意思是我已经编辑了那部分。
标签: c# .net c#-4.0 state-machine