Delegate Usage : Business Applications

后端 未结 8 1201
青春惊慌失措
青春惊慌失措 2021-01-03 02:46

Background

Given that \'most\' developers are Business application developers, the features of our favorite programming languages are used in the context of what we

8条回答
  •  一整个雨季
    2021-01-03 03:28

    Another great use of delegates is as state machines. If your program logic contains repeated if...then statements to control what state it is in, or if you're using complicated switch blocks, you can easily use them to replicate the State pattern.

    enum State {
      Loading,
      Processing,
      Waiting,
      Invalid
    }
    
    delegate void StateFunc();
    
    public class StateMachine  {
      StateFunc[] funcs;   // These would be initialized through a constructor or mutator
      State curState;
    
      public void SwitchState(State state)  {
        curState = state;
      }
    
      public void RunState()  {
        funcs[curState]();
      }
    }
    

    My 2.0 delegate syntax may be rusty, but that's a pretty simple example of a state dispatcher. Also remember that delegates in C# can execute more than one function, allowing you to have a state machine that executes arbitrarily many functions each RunState().

提交回复
热议问题