在下面的代码中,当 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/