Cast to generic type in C#

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

    This is simply not allowed:

    Type key = message.GetType();
    MessageProcessor processor = messageProcessors[key] as MessageProcessor;
    

    You cannot get a generic type as a variable value.

    You'd have to do a switch or something:

    Type key = message.GetType();
    if (key == typeof(Foo))
    {
        MessageProcessor processor = (MessageProcessor)messageProcessors[key];
        // Do stuff with processor
    }
    else if (key == typeof(Bar))
    {
        MessageProcessor processor = (MessageProcessor)messageProcessors[key];
        // Do stuff with processor
    }
    ...
    

提交回复
热议问题