为什么协方差不泛型方法工作 [英] Why covariance does not work with generic method

查看:125
本文介绍了为什么协方差不泛型方法工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有接口和类:

public interface ITree {}
public class Tree : ITree {}

由于的IEnumerable< T> 的,低于code线成功编译:

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:\\实验室\\ Lab.General \\ Lab.General \\ Program.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:\lab\Lab.General\Lab.General\Program.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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆