//public StateMachine() //{ //} public void SetStateForObject <StateEnum>(T entity, Enum state) where StateEnum : struct { IStateObject e = entity as IStateObject; Transition <T> transition = Transitions.Where(t => t.FromState.Equals(StateUtils.GetStateStringAsEnum <StateEnum>(e.GetState())) && t.ToState.Equals(state)).FirstOrDefault(); if (transition != null) { if (transition.Guards != null) { foreach (Func <T, TryGuardResponse> guard in transition.Guards) { TryGuardResponse tgr = guard.Invoke(entity); if (!tgr.Success) { throw new Exception("SetStateFailedError"); } } } e.SetState(state.ToString()); //Effect if (transition.Effect != null) { transition.Effect.Invoke(entity); } } else { throw new Exception("Could not find transition from state " + e.GetState() + " to state " + state.ToString()); } }
public bool TrySetStateForObject <StateEnum>(T entity, Enum state, out List <KeyValuePair <string, string> > errorList) where StateEnum : struct { errorList = new List <KeyValuePair <string, string> >(); IStateObject e = entity as IStateObject; Transition <T> transition = Transitions.Where(t => t.FromState.Equals(StateUtils.GetStateStringAsEnum <StateEnum>(e.GetState())) && t.ToState.Equals(state)).FirstOrDefault(); if (transition != null) { if (transition.Guards != null) { foreach (Func <T, TryGuardResponse> guard in transition.Guards) { TryGuardResponse tgr = guard.Invoke(entity); if (!tgr.Success) { errorList.Add(tgr.Error); } } } if (errorList.Count == 0) { e.SetState(state.ToString()); //Effect if (transition.Effect != null) { transition.Effect.Invoke(entity); } return(true); } } else { errorList.Add(new KeyValuePair <string, string>("NoTransitionError", "Could not find transition from state " + e.GetState() + " to state " + state.ToString())); } return(false); }