daily pastebin goal
73%
SHARE
TWEET

Untitled

a guest Feb 20th, 2019 91 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. using System;
  2. using System.Collections.Generic;
  3.  
  4. namespace TestDynamicMessageHandler
  5. {
  6.     public delegate void HandleObjectDelegate<T>(T obj);
  7.  
  8.     public class DynamicMessageHandler
  9.     {
  10.         private Dictionary<Type, Delegate> _messageHandlers = new Dictionary<Type, Delegate>();
  11.  
  12.         public void RegisterTypeHandler<T>(HandleObjectDelegate<T> handler)
  13.         {
  14.             _messageHandlers.Add(typeof(T), handler);
  15.         }
  16.  
  17.         public bool HandleObject(object message, bool throwException = false)
  18.         {
  19.             var messageType = message.GetType();
  20.  
  21.             if (!_messageHandlers.TryGetValue(messageType, out var handler))
  22.                 if (throwException)
  23.                     throw new NotSupportedException($"The message with type {messageType.Name} is not supported");
  24.                 else
  25.                     return false;
  26.  
  27.             handler.DynamicInvoke(message);
  28.             return true;
  29.         }
  30.     }
  31.  
  32.     // -------------------------------
  33.     public class TestMessage
  34.     {
  35.         public string Name { get; set; }
  36.     }
  37.  
  38.     // -------------------------------
  39.  
  40.     public class SomeOtherMessage
  41.     {
  42.         public string Whatever { get; set; }
  43.     }
  44.  
  45.     // -------------------------------
  46.  
  47.     class Program
  48.     {
  49.         static DynamicMessageHandler _messageHandler = new DynamicMessageHandler();
  50.  
  51.         static void HandleTest(TestMessage test)
  52.         {
  53.             Console.WriteLine(test.Name);
  54.         }
  55.  
  56.         static void HandleSomeOtherMessage(SomeOtherMessage message)
  57.         {
  58.             Console.WriteLine(message.Whatever);
  59.         }
  60.  
  61.         static void Main(string[] args)
  62.         {
  63.             _messageHandler.RegisterTypeHandler<TestMessage>(HandleTest);
  64.             _messageHandler.RegisterTypeHandler<SomeOtherMessage>(HandleSomeOtherMessage);
  65.  
  66.  
  67.             _messageHandler.HandleObject(new TestMessage { Name = "Jeroen" });
  68.             _messageHandler.HandleObject(new SomeOtherMessage { Whatever = "Nothing" });
  69.         }
  70.     }
  71. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top