fork download
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6.  
  7. namespace ConsoleApplication1
  8. {
  9. class Program
  10. {
  11. static void Main(string[] args)
  12. {
  13. var t1 = new Type1();
  14. var t2 = new Type2();
  15. var t3 = new Type3();
  16. var handlers = new Handlers();
  17.  
  18. HandlersStorage.AddHandler<Type1>(handlers.HaldlerOfType1);
  19. HandlersStorage.AddHandler<Type2>(handlers.HaldlerOfType2);
  20. HandlersStorage.AddHandler<Type3>((object o) => { Console.WriteLine("Haldler of Type3 is lambda"); });
  21.  
  22. var a1 = HandlersStorage.GetHandler(t1.GetType());
  23. a1(t1);
  24.  
  25. var a2 = HandlersStorage.GetHandler(t2.GetType());
  26. a2(t2);
  27.  
  28. var a3 = HandlersStorage.GetHandler(t3.GetType());
  29. a3(t3);
  30.  
  31. Console.ReadKey();
  32. }
  33. }
  34.  
  35. public static class HandlersStorage
  36. {
  37. private static Dictionary<Type, Action<object>> _handlers = new Dictionary<Type, Action<object>>();
  38.  
  39. public static void AddHandler<T>(Action<object> action)
  40. {
  41. _handlers.Add(typeof(T),action);
  42. }
  43.  
  44. public static Action<object> GetHandler(Type type)
  45. {
  46. return _handlers[type];
  47. }
  48. }
  49.  
  50. public class Handlers
  51. {
  52. public void HaldlerOfType1(object o)
  53. {
  54. Console.WriteLine("HaldlerOfType1");
  55. }
  56.  
  57. public void HaldlerOfType2(object o)
  58. {
  59. Console.WriteLine("HaldlerOfType2");
  60. }
  61. }
  62.  
  63.  
  64. class Type1
  65. {
  66.  
  67. }
  68.  
  69. class Type2
  70. {
  71.  
  72. }
  73.  
  74. class Type3
  75. {
  76.  
  77. }
  78. }
  79.  
Success #stdin #stdout 0.01s 29672KB
stdin
Standard input is empty
stdout
HaldlerOfType1
HaldlerOfType2
Haldler of Type3 is lambda