根据另一个对象的类型选择/使用带有泛型参数的接口实现
本文关键字:泛型 参数 实现 接口 一个对象 类型 选择 | 更新日期: 2023-09-27 18:03:35
我正在研究一个处理事件的系统:
public interface IEvent { ..}
public class CreateUserEvent : IEvent {...}
public class ChangeUserNameEvent : IEvent {...}
每个事件都有一个特定的处理程序
public interface IEventHandler<T> where T : IEvent { Handle(T @event); }
public class CreateUserEventHandler : IEventHandler<CreateUserEvent> { ... }
public class ChangeUserNameEventHandler : IEventHandler<ChangeUserNameEvent> {...}
到目前为止,一切都很简单。但是,我想为正确的事件创建使用正确事件处理程序的类。
到目前为止,我已经想出了以下方法:
Dictionary<Type, object> EventHandlers; // stores all registered event handlers
// Note that at compile time I do not exactly know the specialization of IEvent
// so I cannot give HandleEvent a generic type parameter :(
void HandleEvent(IEvent @event)
{
// inspect the type of the event handler at runtime
// the event also needs to be dynamic. Even though we know its a
// specialization of IEvent that is compatible with
// the handlers .Handle method
var handler = EventHandlers[@event.GetType()] as dynamic;
hanler.Handle(@event as dynamic);
}
这个解决方案可以工作,但是我必须使用两个动态类型,这让我很担心。我想我可能做了一个错误的设计决定,但我想不出其他的架构/模式来摆脱这些动态。
所以我的问题归结为:我如何选择和使用具有最小运行时内省的泛型接口的正确实现?
注意我更喜欢一个解决方案,其中IEvent和IEventHandler实现完全不知道这个过程
我会尝试一些基于主题
这个解决方案的最大问题是处理程序的类型隐藏在对EventDispatcher的调用中。调度方法。在这个问题中,你声明你想要一个非泛型方法,它没有关于要调度的事件的编译时知识。
public interface IEvent
{
}
public interface IEventHandler<TEvent> where TEvent: IEvent
{
void Handle<TEvent>(TEvent message)
}
public class EventDispatcher
{
private List<object> handlers = new List<object>();
public void Dispatch<TEvent>(TEvent message)
{
foreach (var handler in handlers)
{
if (handler is IEventHandler<TEvent>)
{
var safeHandler = (IEventHandler<TEvent>)handler;
safeHandler.Handle(message);
}
}
}
public IDisposable Register<TEvent>(IEventHandler<TEvent> handler)
{
this.handlers.Add(handler);
return new Subscription(this, handler);
}
class Subscription : IDisposable
{
private EventDispatcher dispatcher;
private IEventHandler<TEvent> handler;
public Subscription(EventDispatcher dispatcher, IEventHandler<TEvent> handler)
{
this.dispatcher = dispatcher;
this.handler = handler;
}
public void Dispose()
{
if (dispatcher == null)
return;
dispatcher.Unsubscribe(handler);
dispatcher = null;
}
}
private void Unsubscribe(IEventHandler<TEvent> handler)
{
this.handlers.Remove(handler);
}
}