首页 > 解决方案 > 如何添加“事件动作“到字典?

问题描述

我有这两个接口:

    public interface IEvent 
    {
        public event Action<EventInfo, EntityEvent.Type, EntityEvent.Property> OnEvent;
        public void SendEvent(EventInfo sendInfo, EntityEvent.Type eventType, Property property);
    }

   public interface IEventListener
   {
       void Listen(EventInfo receiveInfo, EntityEvent.Type eventType, Property property);
   }

我也有这两个类:

    public class EventManager : IEvent
    {
        public event Action<EventInfo, EntityEvent.Type, EntityEvent.Property> OnEvent;
        public void SendEvent(EventInfo sendInfo, EntityEvent.Type eventType, Property property){};
    }


public class EventListener : IEventListener
{
    public virtual void Listen(EventInfo receiveInfo, EntityEvent.Type eventType, Property property)
    {   
    }
}

还有这些其他类:

public class EventInstaller : MonoBehaviour 
{

    private Dictionary<IEvent,Action<EventInfo, EntityEvent.Type, EntityEvent.Property>> eventSender;
 EntityEvent.Property>();

    private Dictionary<IEventListener, Action<EventInfo, EntityEvent.Type, EntityEvent.Property>> eventListerner;
    

    public void AddSender(IEvent sender)
    {
        eventSender.Add(sender, sender.OnEvent);//-->error here
    }


    public void AddListener(IEventListener listener)
    {
        eventListerner.Add(listener, listener.Listen);
    }

我想这样做:

public void Connect()
{       
    foreach (IEvent sender in eventSender.Keys)
    {
        foreach (IEventListener listener in eventListerner.Keys)
        {
            eventSender[sender] += eventListerner[listener];                 
        }
    }
}

错误说:

事件 'OnEvent' 只能出现在 += 或 -= 的左侧

如何修复此错误?太感谢了!!

//------------------------------------------------ -

更新

//------------------------------------------------ -

我这样做是为了解决问题:

  public interface IEvent 
    {
        public event Action<EventInfo, EntityEvent.Type, EntityEvent.Property> OnEvent;
        public void SendEvent(EventInfo sendInfo, EntityEvent.Type eventType, Property property);
    
        public Action<EventInfo, EntityEvent.Type, EntityEvent.Property> GetEvent();
    
    }
    

        public class EventManager : IEvent
        {
    
            public Action<EventInfo, EntityEvent.Type, EntityEvent.Property> GetEvent()
            {
                return  OnEvent;
            }
    }
    
    
    
        
            public void AddSender(IEvent sender)
            {
                eventSender.Add(sender,sender.GetEvent()  );
            }
    
   

     if i do this i have the original reference or is a different instance?..
        

标签: c#dictionaryinterfaceabstract

解决方案


魔术正在从 中删除event关键字IEvent。它可以防止这个委托从外部调用class。此外,anInterface只能包含方法和属性。将字段转换为属性。

public interface IEvent 
{
    public Action<EventInfo, EntityEvent.Type, EntityEvent.Property> OnEvent { get; set; };
    public void SendEvent(EventInfo sendInfo, EntityEvent.Type eventType, Property property);
}

推荐阅读