c# - 泛型 - 当 T 约束为接口(interface)时无法隐式转换,但当 T 为抽象类时则可以

标签 c#

在下面的代码中,当 T: Entity 时,编译器很高兴。

当 T:IEntity 时,我收到“无法隐式转换错误”

不明白为什么?

public abstract class BaseImplementation<T>: ISomeInterface<T> where T: Entity
{
    public abstract T[] GetEntities();

    IEntity[] ISomeInterface.GetEntities()
    {
        return GetEntities();
    }
}

最佳答案

尝试:

where T : class, IEntity

数组的协方差仅适用于引用类型。例如来自MSDN :

For any two reference-types A and B, if an implicit reference conversion (Section 6.1.4) or explicit reference conversion (Section 6.2.3) exists from A to B, then the same reference conversion also exists from the array type A[R] to the array type B[R],

举个例子:

public class Entity : IEntity { }
public struct StructEntity : IEntity { }

然后:

IEntity[] ent1 = new Entity[5];
IEntity[] ent2 = new StructEntity[5];

第二行给出编译错误。

关于c# - 泛型 - 当 T 约束为接口(interface)时无法隐式转换,但当 T 为抽象类时则可以,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35600216/

相关文章:

c# - 如何在 C# 中创建自定义属性

c# - 在派生自 Control 的 ASP.NET 自定义控件中呈现自关闭标记

c# - 是否有用于 long 类型的函数 Math.Pow(A,n) ?

c# - 菜单项突出显示时发生的事件

c# - ADO.NET 中参数化 SQL 命令的最终形式

c# - 为什么 Thread.Sleep 如此有害

c# - Join List<string> 连同最后一个元素的逗号加 "and"

c# - 将数据从子窗体发送到父窗体 TextBox

c# - 列出所有位置的覆盖数据

c# - 如何只发布需要的依赖?