encompass-cs/encompass-cs/MessageManager.cs

46 lines
1.3 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
namespace Encompass
{
internal class MessageManager
{
private readonly Dictionary<Type, List<IMessage>> messageTypeToMessages = new Dictionary<Type, List<IMessage>>();
internal void RegisterMessageType(Type messageType)
{
if (!messageTypeToMessages.ContainsKey(messageType)) {
messageTypeToMessages.Add(messageType, new List<IMessage>());
}
}
internal void AddMessage(IMessage message)
{
var type = message.GetType();
messageTypeToMessages[type].Add(message);
}
internal void AddMessage<TMessage>(IMessage message) where TMessage : struct, IMessage
{
messageTypeToMessages[typeof(TMessage)].Add(message);
}
internal void ClearMessages()
{
foreach (var entry in messageTypeToMessages)
{
entry.Value.Clear();
}
}
internal IEnumerable<TMessage> GetMessagesByType<TMessage>() where TMessage : struct, IMessage
{
return messageTypeToMessages.ContainsKey(typeof(TMessage)) ?
messageTypeToMessages[typeof(TMessage)].Cast<TMessage>() :
Enumerable.Empty<TMessage>();
}
}
}