StateComponent.cs 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Threading.Tasks;
  5. using MineCase.Engine;
  6. using MineCase.Engine.Serialization;
  7. namespace MineCase.Server.Persistence.Components
  8. {
  9. public sealed class InitializeStateMark
  10. {
  11. public static readonly InitializeStateMark Default = new InitializeStateMark();
  12. }
  13. public class StateComponent<T> : Component, IHandle<AfterReadState>, IHandle<BeforeWriteState>
  14. {
  15. public static readonly DependencyProperty<T> StateProperty =
  16. DependencyProperty.Register<T>(nameof(State), typeof(StateComponent<T>));
  17. public T State => AttachedObject.GetValue(StateProperty);
  18. public event AsyncEventHandler<EventArgs> BeforeWriteState;
  19. public event AsyncEventHandler<EventArgs> AfterReadState;
  20. public StateComponent(string name = "state")
  21. : base(name)
  22. {
  23. }
  24. async Task IHandle<AfterReadState>.Handle(AfterReadState message)
  25. {
  26. // 如果为 null 需要初始化状态
  27. if (State == null)
  28. await AttachedObject.SetLocalValue(StateProperty, (T)Activator.CreateInstance(typeof(T), InitializeStateMark.Default));
  29. await AfterReadState.InvokeSerial(this, EventArgs.Empty);
  30. }
  31. Task IHandle<BeforeWriteState>.Handle(BeforeWriteState message)
  32. {
  33. return BeforeWriteState.InvokeSerial(this, EventArgs.Empty);
  34. }
  35. }
  36. }