在下面GetEnumerator()的实现中,编译器拒绝转换List<T>.Enumerator
至IEnumerator<Shape>
即使 T 受 Shape 约束。 (1) 为什么会这样,(2) 有没有我忽略的解决方法?
using System.Collections.Generic;
interface Shape {
void Draw();
}
class Picture<T> : IEnumerable<Shape> where T : Shape {
List<T> shapes;
public IEnumerator<Shape> GetEnumerator()
{
return shapes.GetEnumerator();
}
}
最佳答案
从
更改约束where T : Shape
到
where T : class, Shape
接口(interface)协方差不适用于值类型。
已记录 here :
Variance applies only to reference types; if you specify a value type for a variant type parameter, that type parameter is invariant for the resulting constructed type.
关于c# - 为什么此通用代码中不允许隐式转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68185870/