我有那些类型:

public interface ICommand {}

public class RemoveCommand<T>: ICommand
{
    public int Id {get; set;}
}

public interface ICommandHandler<TCommand> where TCommand: ICommand
{
    void HandleCommand(TCommand command);
}

public class RemoveCommandHandler<T> : ICommandHandler<RemoveCommand<T>>
{
   public void HandleCommand(SoftRemoveCommand<T> command)
   {
       ...
   }
}


当我尝试使用Castle Windsor解析ICommandHandler时,我收到了强制转换异常。所以我这样写:

var obj = new RemoveCommandHandler<RemoveCommand<MyClass>>();
bool t1 = obj is ICommandHandler<RemoveCommand<MyClass>>; //return false!
bool t2 = obj.GetType().IsAssignableFrom(ICommandHandler<RemoveCommand<MyClass>>); //also false!


所以我的问题是:
为什么我的RemoveCommandHandler无法从ICommandHandler分配?

最佳答案

您的通用类声明为RemoveCommandHandler<T>。因此,如果您具有类RemoveCommandHandler<RemoveCommand<MyClass>>,则意味着您的TRemoveCommand<MyClass>

因此,您应该将RemoveCommandHandler<RemoveCommand<MyClass>>更改为RemoveCommandHandler<MyClass>并且代码应该可以工作:

var obj = new RemoveCommandHandler<MyClass>();
bool t1 = obj is ICommandHandler<RemoveCommand<MyClass>>;  // returns true


尽管需要进行第二次检查,但还是要换面:

bool t2 = typeof(ICommandHandler<RemoveCommand<MyClass>>).IsAssignableFrom(obj.GetType());  // returns true

09-17 02:28