implementing a state machine using the “yield” keyword

前端 未结 4 1313
被撕碎了的回忆
被撕碎了的回忆 2020-12-01 05:36

Is it feasible to use the yield keyword to implement a simple state machine as shown here. To me it looks like the C# compiler has done the hard work for you as it internall

4条回答
  •  独厮守ぢ
    2020-12-01 06:09

    While this is not a state machine in the classical sense, the article about Iterator-based Micro Threading uses yield creatively for state-based actions.

    IEnumerable Patrol ()
    {
        while (alive){
            if (CanSeeTarget ()) {
                yield return Attack ();
            } else if (InReloadStation){
                Signal signal = AnimateReload ();
                yield return signal;
            } else {
                MoveTowardsNextWayPoint ();
                yield return TimeSpan.FromSeconds (1);
            };
        }
        yield break;
    }
    

提交回复
热议问题