Cast to generic type in C#

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

    Type type = typeof(MessageProcessor<>).MakeGenericType(key);
    

    That's the best you can do, however without actually knowing what type it is, there's really not much more you can do with it.

    EDIT: I should clarify. I changed from var type to Type type. My point is, now you can do something like this:

    object obj = Activator.CreateInstance(type);
    

    obj will now be the correct type, but since you don't know what type "key" is at compile time, there's no way to cast it and do anything useful with it.

提交回复
热议问题