在下面的代码我希望能够隐式地从投elements至baseElements因为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, …
假设我有接口和类:
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
为什么协方差在这种情况下不起作用?