C# 向下转换泛型类型

C# Downcasting a generic type

interface IMyEvent { }

class SpecificEvent : IMyEvent {  }

interface IMySubscriber<TEvent> where TEvent : IMyEvent { }

class MySubscriber<TEvent> : IMySubscriber<TEvent> where TEvent: IMyEvent { }

class EventPublisher
{
    public void Subscribe(IMySubscriber<IMyEvent> subscriber)
    {

    }
}

我不明白为什么无法使用 MySubscriber<SpecificEvent> 对象执行 Subscribe 方法。

new EventPublisher().Subscribe(new MySubscriber<SpecificEvent>());

它说它不能将 MySubscriber<SpecificEvent> 转换为 IMySubscriber<IMyEvent>。你能解释一下为什么会这样吗,或者提供一些我可以阅读的链接。

为此,您必须使用 out 通用参数标记接口:

interface IMySubscriber<out TEvent> where TEvent : IMyEvent { }

http://rextester.com/FAXW57974

参见:still confused about covariance and contravariance & in/out