Cast to generic type in C#

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

    To convert any type object to a generic type T, the trick is to first assign to an object of any higher type then cast that to the generic type.

    object temp = otherTypeObject;
    T result = (T)temp;
    

提交回复
热议问题