使用此代码
class Program
{
static void Main(string[] args)
{
var eventProvider = new EventProvider();
var eventHandler = new EventHandler();
eventProvider.AddHandler(eventHandler);
var eventInfo = new FiredEventInfo();
Console.WriteLine("Fire without specify generic type parameter");
eventProvider.FireEvent(eventInfo);
Console.WriteLine();
Console.WriteLine("Fire with specify generic type parameter");
eventProvider.FireEvent<HandledEventInfo>(eventInfo);
Console.WriteLine();
Console.ReadKey();
}
}
interface IEventInfo { }
interface HandledEventInfo : IEventInfo { }
class FiredEventInfo : HandledEventInfo { }
interface IEventHandler<in EventInfoType>
where EventInfoType : IEventInfo
{
void Handle(EventInfoType eventInfo);
}
class EventHandler : IEventHandler<HandledEventInfo>
{
public void Handle(HandledEventInfo eventInfo)
{
Console.WriteLine("In EventHandler.Handle(HandledEventInfo eventInfo) { ... }");
}
}
class EventProvider
{
IWindsorContainer _windsorContainer = new WindsorContainer();
public void AddHandler<EventInfoType>(IEventHandler<EventInfoType> eventHandler)
where EventInfoType : IEventInfo
{
_windsorContainer.Register(Component.For<IEventHandler<EventInfoType>>().Instance(eventHandler));
}
public void FireEvent<EventInfoType>(EventInfoType eventInfo)
where EventInfoType : IEventInfo
{
var eventHandlers = _windsorContainer.ResolveAll<IEventHandler<EventInfoType>>();
if (eventHandlers.LongLength > 0)
{
foreach (var eventHandler in eventHandlers)
{
eventHandler.Handle(eventInfo);
}
}
}
}
我有输出
在没有指定泛型类型参数的情况下触发
使用指定泛型类型参数
进行触发在EventHandler.Handle(HandledEventInfo eventInfo){...}
如何在方法FireEvent<>
中没有指定泛型类型参数的情况下调用EvenHandler?