我一直在尝试构建自己的通用状态机,但我想不出一种将状态更改与事件联系起来的方法。
目前,我的通用实现如下:
public interface IStateRoot
{
}
public interface IState<T> where T: IStateRoot
{
}
public abstract class State<T> : IState<T> where T: IStateRoot
{
public delegate void OnChange(IState<T> state);
OnChange OnStateChange;
public void Invoke()
{
OnStateChange?.Invoke(this);
}
}
public class FSM<T> where T: IStateRoot
{
public delegate void TransitionDelegate<K>(IState<K> state) where K: T;
public Dictionary<Type, TransitionDelegate<T>> Transitions;
public State<T> State { get; set; }
public FSM()
{
Transitions = new Dictionary<Type, TransitionDelegate<T>>();
}
public FSM(State<T> init)
{
Transition(init);
}
public void Transition<K>(K nextState) where K : State<T>
{
if (Transitions.TryGetValue(typeof(K), out var value))
{
value?.Invoke(nextState);
}
State = nextState;
}
public void OnTransition<K>(State<K>.OnChange action) where K : T
{
if (Transitions.TryGetValue(typeof(K), out var value))
{
value += action;
return;
}
Transitions.Add(typeof(K), action);
}
}
在一个完美的世界中,我希望能够像这样创建自己的StateRoot
和他的States
public class MyState : IStateRoot
{
public class InitState : State<MyState> { }
public class EndState : State<MyState> { }
}
然后像这样使用它
public class StateListener
{
public FSM<MyState> StateMachine;
public StateListener()
{
StateMachine = new FSM<MyState>();
StateMachine.OnTransition<MyState.InitState>(OnInit);
StateMachine.OnTransition<MyState.EndState>(OnEndState);
StateMachine.Transition(new MyState.InitState());
}
public void OnEndState(MyState.EndState state)
{
Console.WriteLine("EndState");
}
public void OnInit(MyState.InitState state)
{
Console.WriteLine("StartState");
}
}
我在将通用方法挂接到OnTransition
时遇到问题。
我遇到的问题是我无法在OnTransitionMethod中从State<K>.OnChange
转换为FSM<T>.TransitionDelegate<K>
。我不知道该怎么办。