c# - 如何添加“事件动作“到字典?
问题描述
我有这两个接口:
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?..
解决方案
魔术正在从 中删除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);
}
推荐阅读
- python - D-Bus python PyQt5 服务示例
- linux - Linux API:是否可以为单个“write”系统调用指定“O_SYNC”选项
- html - 黑线出现在 Safari 而不是 Chrome 中使用 Ant Design Table
- python - 当值可以为“无”时,将两个字典值一一相除
- indexeddb - IndexedDB:清除并写入单个事务
- javascript - Vue在页面引用上维护路由参数
- python - Azure BLOB PUT Rest api - 无法使用 Python 进行身份验证
- angular-reactive-forms - 反应形式的角度验证日期
- c# - 在所有列表记录中搜索多个空格
- c# - 使用openPDC自动切换ftp连接