无法将通用类型转换为接口

时间:2016-06-19 15:45:28

标签: c# .net generics inheritance casting

我有这些类型:

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分配?

1 个答案:

答案 0 :(得分:4)

您的通用类声明为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