自定义一个事件聚合器

  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;
   
}
posted @ 2024-07-31 05:07  孤沉  阅读(6)  评论(0编辑  收藏  举报