小编Ben*_*Laz的帖子

在C#中理解协方差与泛型的协方差的问题

我无法理解为什么以下C#代码无法编译.

正如您所看到的,我有一个静态泛型方法Something with a IEnumerable<T>parameter(并且T被约束为一个IA接口),并且此参数不能隐式转换为IEnumerable<IA>.

解释是什么?(我不寻找解决方法,只是为了解它为什么不起作用).

public interface IA { }
public interface IB : IA { }
public class CIA : IA { }
public class CIAD : CIA { }
public class CIB : IB { }
public class CIBD : CIB { }

public static class Test
{
    public static IList<T> Something<T>(IEnumerable<T> foo) where T : IA
    {
        var bar = foo.ToList();

        // All those calls are legal
        Something2(new List<IA>()); …
Run Code Online (Sandbox Code Playgroud)

c# covariance contravariance

115
推荐指数
2
解决办法
5197
查看次数

标签 统计

c# ×1

contravariance ×1

covariance ×1