简体   繁体   English

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

[英]Unable to cast generic type to interface

I have those types: 我有那些类型:

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)
   {
       ...
   }
}

While I was trying to resolve my ICommandHandler using Castle Windsor I received a cast exceptions. 当我尝试使用Castle Windsor解析ICommandHandler时,我收到了强制转换异常。 So I wrote this: 所以我这样写:

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!

So my question is: Why my RemoveCommandHandler is not assignable from ICommandHandler? 所以我的问题是:为什么不能从ICommandHandler分配我的RemoveCommandHandler?

Your generic class declaration is RemoveCommandHandler<T> . 您的通用类声明是RemoveCommandHandler<T> So If you have class RemoveCommandHandler<RemoveCommand<MyClass>> , this means that your T is RemoveCommand<MyClass> . 因此,如果您具有类RemoveCommandHandler<RemoveCommand<MyClass>> ,则意味着您的TRemoveCommand<MyClass>

So you should change RemoveCommandHandler<RemoveCommand<MyClass>> to RemoveCommandHandler<MyClass> and the code should work: 因此,您应该将RemoveCommandHandler<RemoveCommand<MyClass>>更改为RemoveCommandHandler<MyClass> ,并且代码应该可以工作:

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

Although for second check you need to switch sides: 尽管需要进行第二次检查,但还是要换面:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM