Cast to generic type in C#

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

    The following seems to work as well, and it's a little bit shorter than the other answers:

    T result = (T)Convert.ChangeType(otherTypeObject, typeof(T));
    

提交回复
热议问题