投射到通用界面

时间:2018-07-10 07:09:34

标签: c# generics interface

我正在编写命令处理模块,但在将实现接口的类强制转换为其通用接口定义时遇到问题。有问题的隔离代码:

public class Program
{
    public interface ICommand
    {
    }

    public class TestCommand : ICommand
    {
        public int Foo { get; set; }
    }

    public interface ICommandHandler<T> where T : ICommand
    {
        void Process(T command);
    }

    public class TestCommandHandler : ICommandHandler<TestCommand>
    {
        public void Process(TestCommand command)
        {
            Console.WriteLine(command.Foo);
        }
    }

    public class CommandHandlersBindings
    {
        private readonly Dictionary<Type, object> commandHandlers;

        public CommandHandlersBindings()
        {
            commandHandlers = new Dictionary<Type, object>();
        }

        public ICommandHandler<T> GetCommandHandler<T>(T command) where T : ICommand
        {
            return (ICommandHandler<T>) commandHandlers[command.GetType()];
        }

        public void RegisterCommandHandler<T>(ICommandHandler<T> handler) where T : ICommand
        {
            commandHandlers[typeof(T)] = handler;
        }
    }


    public static void Main()
    {
        var commandBindings = new CommandHandlersBindings();
        commandBindings.RegisterCommandHandler(new TestCommandHandler());

        ICommand command = new TestCommand();
        var handler = commandBindings.GetCommandHandler(command);

        handler.Process(command);

        Console.ReadKey();
    }
}

问题出在抛出的函数GetCommandHandler中

  

System.InvalidCastException,它无法将类型为'TestCommandHandler'的对象转换为类型为'ICommandHandler`1 [ICommand]'的对象。

在运行时,我只会知道接收到的命令是ICommands,我很喜欢我的字典能够处理该命令。

0 个答案:

没有答案