c# - 为什么此通用代码中不允许隐式转换?

标签 c#

在下面GetEnumerator()的实现中,编译器拒绝转换List<T>.EnumeratorIEnumerator<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/

相关文章:

c# - 连接到服务器 vs 连接到数据库

c# - 在 Silverlight App 中拖放文件夹

c# - 将实例化的 System.Type 作为泛型类的类型参数传递

c# - 在哪里放置 native DLL 以使用 Pocket PC 模拟器?

c# - 任何用于在新行上自动连接的 visual studio 2010 扩展?

C# WPF 从 SQL Server 数据库中检索图像,字节到图像

c# - DrawPath 和 DrawRectangle 的区别

c# - ParentForm 为空(在 Form 内的 UserControl 内的 Button 中)!

c# - Func<...> args 有 "unnamed"个参数。有没有办法给它们命名?

c# - 为什么 CloudTable.ExecuteQuerySegmentedAsync 只返回最大 1k 实体的一小部分?