相关疑难解决方法(0)

这是C#4中的协方差错误吗?

在下面的代码我希望能够隐式地从投elementsbaseElements因为TBase可以隐式转换IBase.

public interface IBase { }
public interface IDerived : IBase { }
public class VarianceBug
{
    public void Foo<TBase>() where TBase : IBase
    {
        IEnumerable<TBase> elements = null;
        IEnumerable<IDerived> derivedElements = null;
        IEnumerable<IBase> baseElements;

        // works fine
        baseElements = derivedElements;

        // error CS0266: Cannot implicitly convert type 
        //   'System.Collections.Generic.IEnumerable<TBase>' to 
        //   'System.Collections.Generic.IEnumerable<IBase>'. 
        //   An explicit conversion exists (are you missing a cast?)
        baseElements = elements;
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,我收到了评论中提到的错误.

引用规范:

A型T<A1, …

c# generics covariance

37
推荐指数
2
解决办法
1659
查看次数

为什么协方差不适用于泛型方法

假设我有接口和类:

public interface ITree {}
public class Tree : ITree {}
Run Code Online (Sandbox Code Playgroud)

由于IEnumerable<T>协变,下面的代码行成功编译:

IEnumerable<ITree> trees = new List<Tree>();
Run Code Online (Sandbox Code Playgroud)

但是当我把它放入通用方法时:

public void Do<T>() where T : ITree
{
     IEnumerable<ITree> trees = new List<T>();
}
Run Code Online (Sandbox Code Playgroud)

我从编译器得到编译错误:

错误1无法将类型'System.Collections.Generic.List'隐式转换为'System.Collections.Generic.IEnumerable'.存在显式转换(您是否缺少演员?)D:\ lab\Lab.General\Lab.General\Program.cs 83 40 Lab.General

为什么协方差在这种情况下不起作用?

c# covariance contravariance c#-4.0

23
推荐指数
1
解决办法
1987
查看次数

标签 统计

c# ×2

covariance ×2

c#-4.0 ×1

contravariance ×1

generics ×1