将实例转换为通用父级时出错

Error on casting a instance to Generic parent

我无法转换为通用父级, 这是我的代码

    public interface IEvent
    {
    }

    public interface IEventHandler<TEvent> where TEvent : IEvent
    {
        Task Handle(TEvent evt);
    }

    public class PersonCreatedEvent : IEvent
    {
        public int Id { get; set; }
    }

    public class PersonCreatedEventHandler : IEventHandler<PersonCreatedEvent>
    {
        public async Task Handle(PersonCreatedEvent evt)
        {
            Console.WriteLine("done");
        }
    }

我的转换代码是这样的:

    var handler = new PersonCreatedEventHandler();

    // exception occurred on this line 
    var cast = (IEventHandler<IEvent>)handler;

但是当我想要施放实例时出现异常。

Unable to cast object of type 'TestProject.ClientApi.PersonCreatedEventHandler' to type 'TestProject.ClientApi.IEventHandler`1[ElearnoInstitute.Endpoint.ClientApi.IEvent]'.

为什么我得到这个异常?以及如何解决这个问题。

禁止强制转换操作,因为它会导致不一致问题。最好用一个例子来解释。

如果我们声明这个class:

public class TestCreatedEvent : IEvent {

}

如果您的代码有效,我们可以这样做:

var handler = new PersonCreatedEventHandler();
var cast = (IEventHandler<IEvent>)handler;
cast.Handle(new TestCreatedEvent());

我们正在将不是 PersonCreatedEvent 的实例传递给处理程序,即 IEventHandler<PersonCreatedEvent> 但不是 IEventHandler<TestCreatedEvent>。 C# 编译器给出错误以防止您可以传递另一个后代类型的实例。

您不能将具有泛型的类型强制转换为同一类型,但泛型是超类型。另一个很好的例子是 List<B>B 扩展 A,并且另一个 class C 也扩展 A。如果可以将 List<B> 转换为 List<A>,则可以将 C 个实例添加到转换的 List<A>,但最初该列表的类型为 List<B>。因此,结果将是您在 List<B> 中有 C 个实例,这是明显的不一致。