Cast to generic type in C#

前端 未结 13 1022
野性不改
野性不改 2021-01-30 20:27

I have a Dictionary to map a certain type to a certain generic object for that type. For example:

typeof(LoginMessage) maps to MessageProcessor

        
13条回答
  •  青春惊慌失措
    2021-01-30 21:21

    Does this work for you?

    interface IMessage
    {
        void Process(object source);
    }
    
    class LoginMessage : IMessage
    {
        public void Process(object source)
        {
        }
    }
    
    abstract class MessageProcessor
    {
        public abstract void ProcessMessage(object source, object type);
    }
    
    class MessageProcessor : MessageProcessor where T: IMessage
    {
        public override void ProcessMessage(object source, object o) 
        {
            if (!(o is T)) {
                throw new NotImplementedException();
            }
            ProcessMessage(source, (T)o);
        }
    
        public void ProcessMessage(object source, T type)
        {
            type.Process(source);
        }
    }
    
    
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary messageProcessors = new Dictionary();
            messageProcessors.Add(typeof(string), new MessageProcessor());
            LoginMessage message = new LoginMessage();
            Type key = message.GetType();
            MessageProcessor processor = messageProcessors[key];
            object source = null;
            processor.ProcessMessage(source, message);
        }
    }
    

    This gives you the correct object. The only thing I am not sure about is whether it is enough in your case to have it as an abstract MessageProcessor.

    Edit: I added an IMessage interface. The actual processing code should now become part of the different message classes that should all implement this interface.

提交回复
热议问题