[英]Using generics with IEnumerable in base class constructor
Why does this code gives this error?为什么此代码会出现此错误?
Argument type 'System.Collections.Generic.IEnumerable<T>' is not assignable to parameter type 'System.Collections.Generic.IEnumerable<[...].IExample>'
参数类型“System.Collections.Generic.IEnumerable<T>”不可分配给参数类型“System.Collections.Generic.IEnumerable<[...].IExample>”
public interface IExample { }
public class BaseClass
{
public BaseClass(IEnumerable<IExample> a) { }
}
public class FailingClass<T> : BaseClass
where T : IExample
{
public FailingClass(IEnumerable<T> a): base(a) { } //error here on base(a)
}
You are missing the class
constraint to T
within FailingClass
.您在
FailingClass
中缺少对T
的class
约束。 IEnumerable<T>
has a type parameter marked as covariant. IEnumerable<T>
具有标记为协变的类型参数。 Covariance enables you to use a more derived type than originally specified.协方差使您能够使用比最初指定的更多派生类型。 Variance in general applies to reference types only.
差异通常仅适用于引用类型。
So what the class constraint actually does here is enforcing a constraint to pass a reference type.所以类约束在这里实际上做的是强制一个约束来传递一个引用类型。 If you were to pass in a value type for T, that type parameter is invariant for the resulting constructed type and does not suffice
IEnumerable<T>
.如果要为 T 传递值类型,则该类型参数对于生成的构造类型是不变的,并且不足以
IEnumerable<T>
。
using System.Collections.Generic;
public interface IExample { }
public class BaseClass
{
public BaseClass(IEnumerable<IExample> a) { }
}
public class FailingClass<T> : BaseClass
where T : class, IExample
{
public FailingClass(IEnumerable<T> a): base(a) { } //error here on base(a)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.