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

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

问题描述

假设我有接口和类:

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屋!

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