deadcode

Members
  • Content count

    1
  • Joined

  • Last visited

Community Reputation

105 Neutral

About deadcode

  • Rank
    Newbie
  1. C# reflection based example using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace Server { //game message class Message { public byte[] Data { get; set; } public byte Opcode { get; set; } } interface IMessageHandler { void DoMessage(Message message); } internal class OpcodeAttribute : Attribute { //or enum public byte Opcode { get; set; } public OpcodeAttribute(byte opcode) { Opcode = opcode; } } [Opcode(5)] class WalkMessageHandler : IMessageHandler { public void DoMessage(Message message) { byte[] bytes = message.Data; //todo parse message } } class MessageHandlerBucket { private readonly Dictionary<byte,IMessageHandler> _handlers = new Dictionary<byte, IMessageHandler>(); /// <summary> /// /// </summary> /// <param name="handlersAssembly">all hanlders in one assembly in this case</param> public MessageHandlerBucket(Assembly handlersAssembly) { IEnumerable<Type> types = handlersAssembly.GetTypes().Where(x => x.IsSubclassOf(typeof (IMessageHandler))); foreach (var type in types) { object opcode = type.GetCustomAttributes(typeof (OpcodeAttribute), true).FirstOrDefault(); if (opcode == null) continue; var opcodeAttribute = (OpcodeAttribute) opcode; byte code = opcodeAttribute.Opcode; var handler = (IMessageHandler) Activator.CreateInstance(type); _handlers.Add(code, handler); } } public void Handle(Message message) { byte opcode = message.Opcode; IMessageHandler handler = _handlers[opcode]; if(handler== null) return;//or throw handler.DoMessage(message); } } }