自定義一個事件聚合器

孤沉發表於2024-07-31
  public interface IEventTransmit
  {
      void Publish<T>(object obj = null) where T : EventBase, new();

      void Subscribe<T>(Action<object> executeMethod) where T : EventBase, new();
  }
  
  public class EventTransmit : IEventTransmit
  {
      private readonly Dictionary<Type, Action<object>> _keyValuePairs = new Dictionary<Type, Action<object>>();
      public void Publish<T>(object obj = null) where T : EventBase, new()
      {
          var eventType = typeof(T);

          if (_keyValuePairs.ContainsKey(eventType))
          {
              _keyValuePairs.TryGetValue(eventType, out var value);
              if (value != null)
              {
                  value.Invoke(Activator.CreateInstance(eventType));
              }
          }
      }

      public void Subscribe<T>(Action<object> executeMethod) where T : EventBase, new()
      {
          var eventType = typeof(T);
          if (!_keyValuePairs.ContainsKey(eventType))
          {
              _keyValuePairs.Add(eventType, executeMethod);

          }
      }
  }
  
   public class StudentEvent: EventBase
 {
     public int Id { get; set; }
     public string Name { get; set; }
 }

 public class EventBase
 {

 }

使用方法
MainWindowViewModel程式碼

 private void ExecutePublish()
 {
     _eventTransmit.Publish<StudentEvent>();
 }

HomeViewModel程式碼

 _eventTransmit.Subscribe<StudentEvent>(ExecuteMethod);

public void ExecuteMethod(object obj)
{
    StudentEvent stu=obj as StudentEvent;
    stu.Name = "Hello";
    Name = stu.Name;
   
}

相關文章