为什么协方差不适用于generics方法
假设我有接口和类:
public interface ITree {} public class Tree : ITree {}
由于IEnumerable
是协变的 ,下面的代码行被成功编译:
IEnumerable trees = new List();
但是当我把它放入通用方法时:
public void Do() where T : ITree { IEnumerable trees = new List(); }
我从编译器得到编译错误:
错误1无法将类型’System.Collections.Generic.List’隐式转换为’System.Collections.Generic.IEnumerable’。 存在显式转换(您是否缺少演员?)D:\ lab \ Lab.General \ Lab.General \ Program.cs 83 40 Lab.General
为什么协方差在这种情况下不起作用?
这是因为方差仅适用于引用类型(类,接口和委托)。 添加一个类约束,它编译得很好:
public static void Do() where T : class, ITree