Cast to generic type in C#

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

    You can write a method that takes the type as a generic parameter:

    void GenericProcessMessage(T message)
    {
        MessageProcessor processor = messageProcessors[typeof(T)]
            as MessageProcessor;
    
        //  Call method processor or whatever you need to do
    }
    

    Then you need a way to call the method with the correct generic argument. You can do this with reflection:

    public void ProcessMessage(object message)
    {
        Type messageType = message.GetType();
        MethodInfo method = this.GetType().GetMethod("GenericProcessMessage");
        MethodInfo closedMethod = method.MakeGenericMethod(messageType);
        closedMethod.Invoke(this, new object[] {message});
    }
    

提交回复
热议问题