Cast to generic type in C#

前端 未结 13 1036
野性不改
野性不改 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

    You can't do that. You could try telling your problem from a more high level point of view (i.e. what exactly do you want to accomplish with the casted variable) for a different solution.

    You could go with something like this:

     public abstract class Message { 
         // ...
     }
     public class Message : Message {
     }
    
     public abstract class MessageProcessor {
         public abstract void ProcessMessage(Message msg);
     }
     public class SayMessageProcessor : MessageProcessor {
         public override void ProcessMessage(Message msg) {
             ProcessMessage((Message)msg);
         }
         public void ProcessMessage(Message msg) {
             // do the actual processing
         }
     }
    
     // Dispatcher logic:
     Dictionary messageProcessors = {
        { typeof(Say), new SayMessageProcessor() },
        { typeof(string), new StringMessageProcessor() }
     }; // properly initialized
    
     messageProcessors[msg.GetType().GetGenericArguments()[0]].ProcessMessage(msg);
    

提交回复
热议问题