假设有一个接口 IQuestion
和该接口的一个实现 AMQuestion
,考虑以下示例:
List<AMQuestion> typed = new List<AMQuestion>();
IList<IQuestion> nonTyped = typed;
这个例子产生了一个编译错误,说两者类型不同,这是预期的结果。但它声明存在一个显式转换。因此,我将其更改为以下内容:
List<AMQuestion> typed = new List<AMQuestion>();
IList<IQuestion> nonTyped = typed as IList<IQuestion>;
然后编译通过,但运行时nonTyped
始终为null。如果有人能解释两件事:
- 为什么这样不起作用。
- 我如何实现所需的效果。
非常感谢。谢谢!
MyClass<T>
的类,那么MyClass<IQuestion>
和MyClass<AMQuestion>
被认为是协变的,因此可以相互转换。 - Will CustodeList<AMQuestion>
作为IEnumerable<IQuestion>
处理。这是因为IEnumerable<IQuestion>
不提供任何机制来_更改_它,因此始终保证类型安全。 编辑:当您使用out
和in
关键字时,就会发挥作用。 - Chris SinclairList<AMQuestion>
未实现IList<IQuestion>
并不意味着不能有一个类继承自该类并实现该接口。 - supercat