这会滥用IEnumerator构造吗?

时间:2012-06-10 17:09:31

标签: c# .net yield state-machine ienumerator

我有一个Sensor状态机,我已经编写了Cycle()个方法:

  /// <summary>
  /// Cycle sets the machine to follow a path from one it's current state to the next. The 
  /// behavior of the sensor is to revert to it's default state should an invalid state be
  /// encountered.
  /// </summary>
  /// <returns></returns>
  public IState Cycle() {
     if(_currentState.Next.IsNullOrEmpty()) {
        _currentState = DefaultState.Set();
     } else {
        _currentState = _currentState.Cycle();
     }
     return _currentState;
  }

  public IEnumerator<IState> Cycle(Func<bool> HasWork) {
     while(HasWork()) {
        yield return Cycle();
     }
  }

实现:

  [TestMethod]
  public void SensorExperiment_CycleWhileFunc() {
     float offset = .5f;
     IState previousState = State.Empty;

     IStimulus temp = new PassiveStimulus(68f) {
        Offset = offset
     };
     ISensor thermostat = new Sensor(65f, 75f, temp);

     int cycles = 0;
     // using this func to tell the machine when to turn off
     Func<bool> hasWork = () => {
        previousState = thermostat.CurrentState;
        // run 10 cycles6
        return cycles++ < 10;
     };

     var iterator = thermostat.Cycle(hasWork);

     while(iterator.MoveNext()) {
        Console.WriteLine("Previous State: {0}\tCurrent State: {1}",
           previousState.Name, iterator.Current.Name);
     }
  }

我已使用IEnumerator 作为状态机读取了Eric Lippert's answer查询。 我的实现是否滥用或利用IEnumerator?我认为我的实现是一种提供状态序列自动化的方法。

1 个答案:

答案 0 :(得分:2)

我认为使用它不是真的是滥用,毕竟,你最多将结果视为一个集合。

另一方面,我认为你没有任何理由在这里使用迭代器。如果你将代码改写为类似下面的内容,那么它应该是一样的。

while (hasWork())
    Console.WriteLine("Previous State: {0}\tCurrent State: {1}",
       previousState.Name, thermostat.Cycle().Name);