NetworkMessageRegistry.cs 1.4 KB

123456789101112131415161718192021222324252627282930313233
  1. using System;
  2. using System.Collections.Generic;
  3. namespace Microsoft.Xna.Framework.Net
  4. {
  5. /// <summary>
  6. /// Provides a registry for network message types, allowing messages to be registered and created dynamically.
  7. /// </summary>
  8. public static class NetworkMessageRegistry
  9. {
  10. private static readonly Dictionary<byte, Func<INetworkMessage>> registry = new();
  11. /// <summary>
  12. /// Registers a network message type with the specified type identifier.
  13. /// </summary>
  14. /// <typeparam name="T">The type of the network message to register. Must implement <see cref="INetworkMessage"/> and have a parameterless constructor.</typeparam>
  15. /// <param name="typeId">The unique identifier for the message type.</param>
  16. public static void Register<T>(byte typeId) where T : INetworkMessage, new()
  17. {
  18. registry[typeId] = () => new T();
  19. }
  20. /// <summary>
  21. /// Creates a network message instance based on the specified type identifier.
  22. /// </summary>
  23. /// <param name="typeId">The unique identifier for the message type.</param>
  24. /// <returns>An instance of the network message, or <c>null</c> if the type identifier is not registered.</returns>
  25. public static INetworkMessage CreateMessage(byte typeId)
  26. {
  27. return registry.TryGetValue(typeId, out var ctor) ? ctor() : null;
  28. }
  29. }
  30. }