LogicEntry.cs 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. using System;
  2. using System.Collections.Generic;
  3. using Component;
  4. namespace Logic
  5. {
  6. public class LogicEntry : ILogicEntry
  7. {
  8. private readonly Dictionary<short, IHandler> handlers = new Dictionary<short, IHandler>();
  9. public LogicEntry()
  10. {
  11. Type[] types = typeof (LogicEntry).Assembly.GetTypes();
  12. foreach (var type in types)
  13. {
  14. object[] attrs = type.GetCustomAttributes(typeof(HandlerAttribute), false);
  15. if (attrs.Length == 0)
  16. {
  17. continue;
  18. }
  19. var handler = (IHandler)Activator.CreateInstance(type);
  20. short opcode = ((HandlerAttribute)attrs[0]).Opcode;
  21. if (handlers.ContainsKey(opcode))
  22. {
  23. throw new Exception(string.Format(
  24. "same opcode, opcode: {0}, name: {1}", opcode, type.Name));
  25. }
  26. handlers[opcode] = handler;
  27. }
  28. }
  29. public void Enter(MessageEnv messageEnv, short opcode, byte[] content)
  30. {
  31. IHandler handler = null;
  32. if (!handlers.TryGetValue(opcode, out handler))
  33. {
  34. throw new Exception(string.Format("not found handler opcode {0}", opcode));
  35. }
  36. handler.Handle(messageEnv, content);
  37. }
  38. }
  39. }