Command.cs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. using System;
  2. namespace etoy
  3. {
  4. abstract class Command : IContextSetter, ICommand
  5. {
  6. bool _completed;
  7. bool _running;
  8. float _progress;
  9. Exception _exception;
  10. void IContextSetter.SetContext(Context context) => Context = context;
  11. bool ICommand.Start => _running;
  12. bool ICommand.Done => _completed;
  13. float ICommand.Progress => _progress;
  14. Exception ICommand.Exception => _exception;
  15. void ICommand.Execute()
  16. {
  17. if (!_running)
  18. {
  19. _running = true;
  20. OnProcess();
  21. }
  22. }
  23. /// <summary>
  24. /// 上下文
  25. /// </summary>
  26. protected Context Context { get; private set; }
  27. /// <summary>
  28. /// 异步完成
  29. /// </summary>
  30. protected void Completed()
  31. {
  32. _progress = 1.0f;
  33. _completed = true;
  34. }
  35. protected void SetException(Exception e)
  36. {
  37. _exception = e;
  38. }
  39. /// <summary>
  40. /// 设置进度
  41. /// </summary>
  42. /// <param name="progress"></param>
  43. protected void SetProgress(float progress)
  44. {
  45. if (progress >= 1.0f)
  46. _progress = 1.0f;
  47. else if (progress < 0.0f)
  48. _progress = 0.0f;
  49. else
  50. _progress = progress;
  51. }
  52. /// <summary>
  53. /// 处理回调
  54. /// </summary>
  55. protected abstract void OnProcess();
  56. /// <summary>
  57. /// 命令描述, 用于显示在控制台上
  58. /// </summary>
  59. public abstract string Description { get; }
  60. }
  61. }