Cast to generic type in C#

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

    As mentioned, you cannot cast it directly. One possible solution is to have those generic types inherit from a non-generic interface, in which case you can still invoke methods on it without reflection. Using reflection, you can pass the mapped object to any method expecting it, then the cast will be performed for you. So if you have a method called Accept expecting a MessageProcessor as a parameter, then you can find it and invoke it dynamically.

提交回复
热议问题