我想在通用字典中添加项目。这是我的示例:
public class EventHandlerService : IEventHandlerService
{
private readonly Dictionary<EventType, IEventHandler<IEvent>> handlerDictionary = new Dictionary<EventType, IEventHandler<IEvent>>();
public EventHandlerService(IAzureBlobStorage azureBlobStorage)
{
handlerDictionary.Add(EventType.CARD_BLOCK, new CardBlockedEventHandler(azureBlobStorage));
}
public void HandleCommand(IEvent @event, ILogger log)
{
var commandHandler = handlerDictionary[@event.EventType];
commandHandler.HandleAsync(@event, log);
}
}
IEvent处理程序:
public interface IEventHandler<TEvent> where TEvent : IEvent
{
/// <summary>
///
/// </summary>
/// <param name="event"></param>
Task HandleAsync(TEvent @event, ILogger logger);
}
处理程序:
public class CardBlockedEventHandler : IEventHandler<CardBlockedEvent>
{
private readonly IAzureBlobStorage _azureBlobStorage;
public CardBlockedEventHandler(IAzureBlobStorage azureBlobStorage)
{
_azureBlobStorage = azureBlobStorage;
}
public async Task HandleAsync(CardBlockedEvent cardBlockedEvent, ILogger log)
{
log.LogInformation($"Card blocked event received for account - {cardBlockedEvent.Message}");
throw new NotImplementedException();
}
}
IEvent接口:
public interface IEvent
{
EventType EventType { get; }
}
我可以创建一种通用词典吗?或者,我只能使用非通用IEventHandler进行创建。
想法?
已经有通用词典:
Dictionary<TKey,TValue>
https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2
我从Framework 2.0起就存在。确实,非通用版本是人们经常忘记的东西(或被上瘾者使用)的奇怪版本。