为什么协方差不适用于泛型方法 [英] Why covariance does not work with generic method
问题描述
假设我有接口和类:
public interface ITree {}
public class Tree : ITree {}
由于IEnumerable
是协变,下面的代码行编译成功:
As IEnumerable<T>
is covariant, the code line below is compiled successfully:
IEnumerable<ITree> trees = new List<Tree>();
但是当我把它放到泛型方法中时:
But when I put it into generic method:
public void Do<T>() where T : ITree
{
IEnumerable<ITree> trees = new List<T>();
}
我从编译器得到编译错误:
I get compiled error from compiler:
错误 1 无法将类型System.Collections.Generic.List"隐式转换为System.Collections.Generic.IEnumerable".存在显式转换(您是否缺少演员表?) D:labLab.GeneralLab.GeneralProgram.cs 83 40 Lab.General
Error 1 Cannot implicitly convert type 'System.Collections.Generic.List' to 'System.Collections.Generic.IEnumerable'. An explicit conversion exists (are you missing a cast?) D:labLab.GeneralLab.GeneralProgram.cs 83 40 Lab.General
为什么协方差在这种情况下不起作用?
Why covariance does not work in this case?
推荐答案
那是因为变体只适用于引用类型(类、接口和委托).添加一个类约束,它编译得很好:
That is because variance only works with reference types (classes, interfaces & delegates). Add a class constraint and it compiles just fine:
public static void Do<T>() where T : class, ITree
这篇关于为什么协方差不适用于泛型方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!